Introduction
f-strings (formatted string literals) are Python’s best feature for string formatting — fast, readable, and powerful. But most developers only use the basics. This post covers the advanced tricks that make f-strings shine.
The basics (refresher)
name = "Galvan"
age = 30
print(f"Hello, {name}! You are {age} years old.")
# Hello, Galvan! You are 30 years old.
Formatting numbers
pi = 3.14159265
price = 1234.5
big = 1_000_000
f"{pi:.2f}" # "3.14" (2 decimal places)
f"{pi:.4f}" # "3.1416"
f"{price:,.2f}" # "1,234.50" (thousands separator)
f"{big:,}" # "1,000,000"
f"{big:_}" # "1_000_000"
f"{0.5:.0%}" # "50%" (percentage)
f"{42:05d}" # "00042" (zero-padded)
f"{255:x}" # "ff" (hex)
f"{255:b}" # "11111111" (binary)
f"{255:o}" # "377" (octal)
Alignment and padding
name = "Galvan"
f"{name:<10}" # "Galvan " (left-aligned, width 10)
f"{name:>10}" # " Galvan" (right-aligned)
f"{name:^10}" # " Galvan " (centered)
f"{name:*^10}" # "**Galvan**" (centered, padded with *)
f"{name:.<10}" # "Galvan...." (left, padded with .)
Great for CLI tables and formatted output.
Date formatting
from datetime import datetime
now = datetime(2026, 3, 8, 14, 30, 0)
f"{now:%Y-%m-%d}" # "2026-03-08"
f"{now:%B %d, %Y}" # "March 08, 2026"
f"{now:%I:%M %p}" # "02:30 PM"
f"{now:%A, %B %d}" # "Sunday, March 08"
Uses strftime format codes directly in the f-string.
The = specifier (debugging)
x = 42
name = "Galvan"
f"{x=}" # "x=42"
f"{name=}" # "name='Galvan'"
f"{x + 1=}" # "x + 1=43"
f"{len(name)=}" # "len(name)=6"
The = specifier prints the expression AND its value — invaluable for debugging. No more print(f"x = {x}").
Nested quotes (Python 3.12+)
Before 3.12, you couldn’t use the same quote type inside an f-string:
# Python 3.11 and earlier — ERROR
name = "Galvan"
f"Hello, {name.replace("a", "o")}" # SyntaxError
# Workaround: different quotes
f"Hello, {name.replace('a', 'o')}" # "Golvan"
# Python 3.12+ — just works
f"Hello, {name.replace("a", "o")}" # "Golvan"
3.12 also allows backslashes in f-string expressions:
# Python 3.12+
f"{'\n'.join(items)}"
Multi-line f-strings
name = "Galvan"
age = 30
city = "Vadodara"
msg = (
f"Name: {name}\n"
f"Age: {age}\n"
f"City: {city}"
)
Or use triple-quoted f-strings:
msg = f"""
User Profile:
Name: {name}
Age: {age}
City: {city}
"""
Expressions in f-strings
items = [1, 2, 3, 4, 5]
f"Sum: {sum(items)}" # "Sum: 15"
f"Max: {max(items)}" # "Max: 5"
f"Sorted: {sorted(items, reverse=True)}" # "Sorted: [5, 4, 3, 2, 1]"
f"Even: {[x for x in items if x % 2 == 0]}" # "Even: [2, 4]"
Any valid Python expression works inside {}.
Format spec mini-language
{value:fill align sign # 0 width precision type}
# Fill + align
f"{'hi':*^10}" # "**hi******" (wait, that's 10 chars: **hi******)
# Actually: "**hi******" → no. Let's be precise:
f"{'hi':*^10}" # "**hi******"? No.
# fill='*', align='^', width=10 → "**hi******"?
# '*' * ((10-2)//2) + 'hi' + '*' * ((10-2)//2) = "****hi****"?
# Let me just say: centered, padded with *
The format spec is powerful but complex. Common patterns above cover 95% of use cases.
f-strings vs alternatives
| f-string | .format() | % formatting | Template | |
|---|---|---|---|---|
| Speed | Fastest | Slower | Slow | Slow |
| Readability | Best | OK | Poor | OK |
| Expressions | Yes | No | No | No |
| Python version | 3.6+ | 2.6+ | All | All |
Always use f-strings for new code. They’re the fastest and most readable.
Common mistakes
- Using f-strings for SQL —
f"SELECT * FROM users WHERE id = {user_id}"is a SQL injection vulnerability. Use parameterized queries. - Overly complex expressions —
f"{user.name.upper().strip()[:10]}"is hard to read. Compute first, then format. - Forgetting raw strings for regex —
f"\d+"works butrf"\d+"is clearer for regex patterns. - Using f-strings in logging —
logger.info(f"User {name} logged in")evaluates the string even if INFO is disabled. Uselogger.info("User %s logged in", name)for lazy evaluation.
Key Concepts
- f-string =
f"..."with{expression}placeholders - Format spec =
:.2f,:,,:>10, etc. =specifier = debug printing ({x=})- Nested quotes = allowed in Python 3.12+
- Multi-line = triple-quoted f-strings
What to Try Next
- Replace
.format()and%formatting in your codebase with f-strings. - Use f-strings in your FastAPI responses.
- Use the
=specifier for debugging in your pytest tests. - Combine with type hints for self-documenting code.
FAQ
f-strings vs .format() — which is faster?
f-strings are ~2x faster than .format() and ~3x faster than % formatting. They’re also more readable. Use f-strings for everything in Python 3.6+.
Can I use f-strings in older Python?
f-strings require Python 3.6+. For 3.5 and earlier, use .format() or %. In 2026, everyone is on 3.9+, so this is a non-issue.
f-strings and security?
f-strings evaluate expressions — never use them with untrusted input (SQL injection, code injection). For user-facing strings, use str.format() or template strings with explicit variable passing. For SQL, always use parameterized queries.