f-Strings and String Formatting
Python · Core Language · Run with python3
Explanation
f-strings (PEP 498, Python 3.6+) embed expressions in string literals: `f"{expr}"`. They call `__format__` on the object with an optional format spec after `:`. Python 3.12 removed the restriction that f-string expressions couldn't contain the same quote type as the outer string. `=` suffix (`f"{value=}"`) prints both the expression text and its value — a debug shorthand.
Real-World Scenario
Formatting financial reports, generating SQL (carefully — prefer parameterized queries), building log messages, and rendering templates all use f-strings in modern Python. The `format_spec` mini-language handles padding, alignment, number formatting, and date formatting without importing a library. ```python import math from datetime import datetime # Format spec: [[fill]align][sign][#][0][width][grouping][.prec][type] pi = math.pi salary = 123456.789 now = datetime.now() print(f"{pi:.4f}") # 3.1416 print(f"{salary:>15,.2f}") # 123,456.79 (right-aligned, 15 wide) print(f"{42:#010b}") # 0b00101010 (binary with prefix, 10 wide) print(f"{now:%Y-%m-%d}") # 2024-01-15 (date format) # Debug shorthand (Python 3.8+) x = [1, 2, 3] print(f"{x=}") # x=[1, 2, 3] # Nested f-strings and Python 3.12 same-quote expressions items = ["a", "b", "c"] print(f"{'|'.join(items)}") # a|b|c (Python 3.12+: same quote inside) ```
Quick Snippet
import math
from datetime import datetime
# Format spec: [[fill]align][sign][#][0][width][grouping][.prec][type]
pi = math.pi
salary = 123456.789
now = datetime.now()
print(f"{pi:.4f}") # 3.1416
print(f"{salary:>15,.2f}") # 123,456.79 (right-aligned, 15 wide)
print(f"{42:#010b}") # 0b00101010 (binary with prefix, 10 wide)
print(f"{now:%Y-%m-%d}") # 2024-01-15 (date format)
# Debug shorthand (Python 3.8+)
x = [1, 2, 3]
print(f"{x=}") # x=[1, 2, 3]
# Nested f-strings and Python 3.12 same-quote expressions
items = ["a", "b", "c"]
print(f"{'|'.join(items)}") # a|b|c (Python 3.12+: same quote inside)Full Example
# Compile: python3 fstrings.py
# Output:
# 3.1416
# a|b|c
import math
pi = math.pi
salary = 123456.789
print(f"{pi:.4f}")
print(f"{salary:>15,.2f}")
print(f"{42:#010b}")
# Debug shorthand (Python 3.8+)
x = [1, 2, 3]
print(f"{x=}")
# Nested f-string
items = ["a", "b", "c"]
print(f"{'|'.join(items)}")
# Multiline f-string
name = "Alice"
score = 98.5
report = (
f"Student: {name}\n"
f"Score: {score:.1f}\n"
f"Grade: {'A' if score >= 90 else 'B'}"
)
print(report)
python3 fstrings.py