Topic 31 of 64
f-strings
Overview
f-strings (formatted string literals, introduced in Python 3.6) are the modern, fastest, and most readable way to embed expressions inside strings. They outperform % formatting and .format() in both speed and clarity.
Syntax
python
name = "Alice"
age = 30
pi = 3.14159
f"Hello, {name}!" # "Hello, Alice!"
f"{name} is {age} years old" # "Alice is 30 years old"
f"Pi is {pi:.2f}" # "Pi is 3.14" (format spec)
f"{2 ** 10}" # "1024" (expressions)
f"{name!r}" # "'Alice'" (repr)
f"{age:>5}" # " 30" (right-align width 5)Common Pitfalls
- f-strings execute the expression at runtime — avoid putting side effects (function calls with mutations) inside them.
- For Python 3.12+, use f'{value=}' for debug output: f'{x=}' prints 'x=42'.
- Interview tip: f-strings are faster than .format() because they are parsed at compile time into bytecode.
Real-World Example
Format a financial report row with alignment and decimal precision
example
python
def format_row(product: str, price: float, qty: int) -> str:
total = price * qty
p_col = f"{product:20}"
pr_col = f"${price:9.2f}"
q_col = f"x{qty:4}"
t_col = f"= ${total:11.2f}"
return f"{p_col} {pr_col} {q_col} {t_col}"
print(format_row("Laptop", 999.99, 3))
# Laptop $ 999.99 x 3 = $2999.97