f-strings & Formatting
beginner12 min readLesson 12 of 169
Embed values in text, format numbers, escapes, and multiline strings.
f-strings embed values inside text — the modern standard for output:
name = "Minh"
age = 21
print(f"{name} is {age}") # Minh is 21
print(f"Next year: {age + 1}") # expressions allowed!
The f prefix turns the string into a template: anything inside {} is
evaluated. This one feature replaces a whole zoo of older formatting tricks.
Formatting numbers
Add a format spec after ::
price = 7.5
print(f"{price:.2f}") # 7.50 (2 decimals)
ratio = 0.876
print(f"{ratio:.0%}") # 88%
n = 1234567
print(f"{n:,}") # 1,234,567
Escapes and multiline
\n is a newline, \t a tab, \\ a literal backslash. For text with both
quote styles or many lines, use triple quotes:
menu = '''1. Start
2. Settings
3. Quit'''