What is string formatting and how do I use it in Python?
· Category: Python Programming
Short answer
Python offers three main ways to format strings: f-strings (recommended, Python 3.6+), the .format() method, and the legacy % operator. F-strings are the most readable and performant.
How it works
F-strings evaluate expressions inside curly braces at runtime:
name = "Bob"
score = 95.7
print(f"{name} scored {score:.1f}%")
The .format() method replaces {} placeholders with arguments:
print("{} scored {:.1f}%".format(name, score))
Legacy % formatting uses format specifiers like C's printf:
print("%s scored %.1f%%" % (name, score))
Example
Formatting numbers, dates, and alignment:
value = 12345.6789
print(f"Currency: ${value:,.2f}")
# Alignment
for item in ["apple", "pie"]:
print(f"Item: {item:>10}")
# Expressions inside f-strings
a, b = 5, 3
print(f"{a} + {b} = {a + b}")
Why it matters
Readable formatting reduces bugs and makes code maintenance easier. F-strings also tend to be faster than .format() because the expressions are parsed at compile time.
Common issues
- Forgetting the
fprefix on f-strings results in literal braces instead of interpolation. - Incorrect format specifiers can raise
ValueError. - F-strings cannot contain backslashes inside expression braces.