Python Format Strings
Format strings let you insert values directly into text, producing clean and readable output.
The Problem With Concatenation
Building output by joining strings with the + operator gets clumsy fast, especially when numbers are involved, because Python will not glue a string and a number together automatically. Format strings solve this by letting you drop values straight into a text template.
Why + gets awkward
name = "Sam"
age = 30
# This raises a TypeError:
# print("Age: " + age)
# You would have to convert first:
print("Age: " + str(age))f-strings
The modern and preferred approach is the f-string, introduced in Python 3.6. Put the letter f right before the opening quote, then wrap any variable or expression in curly braces inside the text. Python evaluates whatever is between the braces and inserts the result.
Using f-strings
name = "Sam"
age = 30
print(f"{name} is {age} years old.")
print(f"Next year {name} will be {age + 1}.")
print(f"{name.upper()} has {len(name)} letters.")Format Specifiers
After a value inside the braces you can add a colon followed by formatting instructions. These control decimal places, padding, alignment, and more, which is especially useful for money, percentages, and neatly aligned tables.
Controlling the output
price = 1234.5
ratio = 0.8756
print(f"Total: ${price:,.2f}")
print(f"Score: {ratio:.1%}")
print(f"|{'left':<10}|{'right':>10}|")- f-strings are the recommended style for new Python 3 code.
- The older str.format() method uses the same braces but takes values as arguments.
- The oldest percent-style formatting, such as '%s' % value, still works but is rarely chosen today.
- Always prefer readability: f-strings keep the value right next to where it appears in the text.