Introduction To F-String
Introduction To F-String
The f-string (formatted string literal) in Python is a concise and readable way to embed
expressions inside string literals using curly braces {} . It was introduced in Python 3.6 and
provides an elegant alternative to the older format() method and the % operator for string
formatting.
Syntax of f-string
To create an f-string, you simply prefix the string with an f or F , and within the curly braces {} ,
you can insert any valid Python expression, including variables, functions, or more complex
expressions.
name = "Alice"
age = 25
greeting = f"Hello, {name}. You are {age} years old."
print(greeting)
Output:
price = 99.99
product = "laptop"
message = f"The price of the {product} is ${price}."
print(message)
Output:
width = 5
height = 10
area = f"The area is {width * height} square units."
print(area)
Output:
3. Calling Functions:
You can call functions inside f-strings:
def double(x):
return x * 2
value = 5
result = f"Double of {value} is {double(value)}."
print(result)
Output:
Double of 5 is 10.
4. Formatting Numbers:
f-strings allow you to format numbers, such as specifying decimal places, commas for
large numbers, or even scientific notation.
pi = 3.14159
formatted_pi = f"Pi rounded to two decimals is {pi:.2f}."
print(formatted_pi)
Output:
Output:
1,000,000
5. Multiline f-strings:
You can use multiline f-strings by simply wrapping the string in triple quotes ( """ or
''' ):
name = "Alice"
message = f"""
Dear {name},
Regards,
The Team
"""
print(message)
Output:
Advantages of f-strings
1. Readability: f-strings make the code more readable by embedding expressions directly in
the string.
2. Efficiency: f-strings are faster than other string formatting methods like % and
.format() because they are evaluated at runtime.
3. Simplicity: They are easier to write and debug compared to other formatting approaches.