String formatting in Python allows you to inject variables into strings in a readable and flexible way. This guide covers different string formatting techniques, including f-strings, the format() method, and the older %-style formatting.
1. f-Strings (Python 3.6+)
f-strings, or formatted string literals, are the most modern and convenient way to format strings in Python. You can embed expressions inside curly braces {}, and they will be evaluated at runtime.
# Using f-strings
name = "Alice"
age = 30
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string) # Output: My name is Alice and I am 30 years old.
Advantages: f-strings are concise, readable, and support any valid Python expression.
Example with Expressions:
# Using expressions inside f-strings
x = 5
y = 10
result = f"The sum of {x} and {y} is {x + y}."
print(result) # Output: The sum of 5 and 10 is 15.
2. format() Method
The format() method allows you to insert variables into placeholders marked by curly braces {}. It provides more control over formatting options.
# Using format() method
name = "Bob"
age = 40
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string) # Output: My name is Bob and I am 40 years old.
Positional and Keyword Arguments:
# Positional arguments
formatted_string = "I have {0} apples and {1} oranges.".format(5, 3)
print(formatted_string) # Output: I have 5 apples and 3 oranges.
# Keyword arguments
formatted_string = "My name is {name} and I live in {city}.".format(name="Charlie", city="Paris")
print(formatted_string) # Output: My name is Charlie and I live in Paris.
Formatting Numbers:
# Formatting numbers
pi = 3.14159265358979
formatted_pi = "Pi rounded to 2 decimal places: {:.2f}".format(pi)
print(formatted_pi) # Output: Pi rounded to 2 decimal places: 3.14
3. % Formatting (Old Style)
This older style of string formatting uses the % operator to insert values into a string. While still supported, it is less commonly used in modern Python code.
# Using % formatting name = "David" age = 35 formatted_string = "My name is %s and I am %d years old." % (name, age) print(formatted_string) # Output: My name is David and I am 35 years old.
Formatting Numbers with %:
# Formatting numbers with % pi = 3.14159 formatted_pi = "Pi rounded to 2 decimal places: %.2f" % pi print(formatted_pi) # Output: Pi rounded to 2 decimal places: 3.14
4. Template Strings (from the string Module)
Template strings offer another way to format strings using placeholders marked by $. They are simpler and more secure for certain applications, such as user-generated input.
from string import Template
template = Template("My name is $name and I am $age years old.")
formatted_string = template.substitute(name="Eve", age=28)
print(formatted_string) # Output: My name is Eve and I am 28 years old.
Comparison of String Formatting Methods
| Method | Introduced in | Advantages | Disadvantages |
|---|---|---|---|
| f-strings | Python 3.6 | Concise, readable, supports expressions | Not available in Python versions below 3.6 |
| format() | Python 2.7 and 3.0+ | Flexible, supports positional and keyword arguments | More verbose than f-strings |
| % Formatting | Python 2.x | Simple for basic formatting | Limited flexibility, less readable |
| Template Strings | Python 2.4 | Safe for user-generated input | Less powerful for complex expressions |
Conclusion
Python provides multiple ways to format strings, each with its own strengths. For modern Python code, f-strings are the recommended approach due to their readability and performance.