String formatting is an essential skill in Python, allowing you to dynamically insert variables and expressions into strings. Python supports multiple ways to format strings, each with its own use cases.
%
OperatorThe %
operator is an older way to format strings, reminiscent of C-style formatting.
name = "Alice"
age = 30
formatted_string = "My name is %s and I am %d years old." % (name, age)
print(formatted_string)
Output:
My name is Alice and I am 30 years old.
%s
: String%d
: Integer%f
: Float%.2f
: Float with two decimal placesThe %
operator is considered outdated and less readable compared to newer methods. Use it only for legacy code.
str.format()
MethodIntroduced in Python 3, the str.format()
method provides a more versatile and readable way to format strings.
name = "Bob"
age = 25
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)
Output:
My name is Bob and I am 25 years old.
# Positional arguments
"{0} is {1} years old.".format("Charlie", 35)
# Keyword arguments
"{name} is {age} years old.".format(name="Daisy", age=40)
value = 123.4567
print("The value is {:.2f}".format(value))
Output:
The value is 123.46
Use str.format()
for Python versions below 3.6 where f-strings are not supported.
Introduced in Python 3.6, f-strings (formatted string literals) offer the most concise and readable way to format strings.
name = "Eve"
age = 28
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)
Output:
My name is Eve and I am 28 years old.
radius = 5
area = 3.14159 * radius**2
print(f"The area of a circle with radius {radius} is {area:.2f}")
Output:
The area of a circle with radius 5 is 78.54
F-strings are both faster and more readable compared to other methods. They are ideal for modern Python code.
Feature | % Operator | str.format() | F-Strings |
---|---|---|---|
Readability | Low | Moderate | High |
Speed | Moderate | Moderate | High |
Python Version Support | Legacy | Python 3+ | Python 3.6+ |
Consider using f-strings in all new Python code to maintain readability and performance.
Use the %
operator to format the following string:
Example:
name = "Frank"
age = 45
print("Name: %s, Age: %d" % (name, age))
Format a string with str.format()
to display a price with two decimal places:
Example:
price = 19.995
print("The price is {:.2f}".format(price))
Use f-strings to display the square of a number:
Example:
number = 8
print(f"The square of {number} is {number**2}")