Basic Usage
Here's a basic example of using f-strings:
name = "Alice"
age = 30
greeting = f"Hello, my name is {name} and I am {age} years old."
print(greeting)
Hello, my name is Alice and I am 30 years old.
Embedding Expressions
You can also embed expressions directly inside f-strings:
length = 5
width = 3
area = f"The area of the rectangle is {length * width} square units."
print(area)
The area of the rectangle is 15 square units.
Formatting Numbers
F-strings also allow you to format numbers:
pi = 3.141592653589793
formatted_pi = f"Pi rounded to two decimal places is {pi:.2f}."
print(formatted_pi)
Pi rounded to two decimal places is 3.14.
Using Functions Inside F-Strings
You can even call functions within an f-string:
def greet(name):
return f"Hello, {name}!"
message = f"{greet('Alice')}"
print(message)
Hello, Alice!
Multi-line F-Strings
F-strings can also be used with multi-line strings:
name = "Alice"
age = 30
info = (
f"Name: {name}\n"
f"Age: {age}\n"
f"Location: Wonderland"
)
print(info)
Name: Alice
Age: 30
Location: Wonderland
Combining F-Strings with Other String Formatting
F-strings can be combined with other string formatting methods if necessary:
name = "Alice"
age = 30
combined = f"Name: {name}, " + "Age: {}".format(age)
print(combined)
Name: Alice, Age: 30
0 Comments:
Post a Comment