Format Strings
Formatting Methods
Python provides multiple ways to insert values into strings. The most common are f-strings (introduced in Python 3.6), str.format(), and the older % formatting. All three achieve similar results but differ in readability and flexibility.
Example
# f-strings (Python 3.6+)
name = "Alice"
age = 25
f_string = f"{name} is {age} years old"
print(f_string)
# str.format()
format_string = "{} is {} years old".format(name, age)
print(format_string)
# % formatting (legacy)
percent_string = "%s is %d years old" % (name, age)
print(percent_string)
Output
Alice is 25 years old Alice is 25 years old Alice is 25 years old
f-string Features
f-strings support inline expressions, function calls, alignment, formatting options, and even nesting. They are concise and efficient since they are evaluated at runtime.
Feature | Example |
---|---|
Expressions | f"{2 * 3}" → '6' |
Method calls | f"{'text'.upper()}" → 'TEXT' |
Formatting | f"{3.14159:.2f}" → '3.14' |
Alignment | f"{'text':<10}" → 'text ' |
Nested | f"{f'{name}'}" → 'Alice' |
Advanced Formatting
Formatting can include numbers, dates, and debugging output. The = specifier in f-strings makes debugging easier by printing both the variable name and its value.
Example
# Number formatting
price = 19.99
print(f"Price: ${price:.2f}") # 'Price: $19.99'
# Date formatting
from datetime import datetime
now = datetime.now()
print(f"Today is {now:%B %d, %Y}") # e.g., 'Today is June 15, 2023'
# Debugging with =
value = 42
print(f"{value=}") # 'value=42'
ℹ️ Note: f-strings are evaluated at runtime and are the recommended approach in Python 3.6+.