Python Tutorial · Python Basics · Lesson 10 of 42
Python String Formatting
Build strings with f-strings, format specifiers and join().
f-strings
Put an f before the quotes and write expressions inside { } — the clearest way to format strings since Python 3.6.
name = "Ada"
age = 36
print(f"{name} is {age} years old")
print(f"Next year she will be {age + 1}")
Output
Ada is 36 years old Next year she will be 37
Format specifiers
After a colon you can control how values are shown: decimals, thousands separators, padding and percentages.
price = 1234.5
ratio = 0.4567
print(f"{price:.2f}")
print(f"{price:,.2f}")
print(f"{ratio:.1%}")
print(f"[{'left':<8}] [{'right':>8}] [{'mid':^8}]")
print(f"{42:05d}")
Output
1234.50 1,234.50 45.7% [left ] [ right] [ mid ] 00042
Debugging with =
{name=} prints both the expression and its value — handy for quick debugging.
x = 7
y = 3
print(f"{x=} {y=} {x * y=}")
Output
x=7 y=3 x * y=21
Building strings in loops
Concatenating with + in a loop creates many temporary strings. Collect parts in a list and join() them:
rows = [("apples", 3), ("pears", 5)]
lines = [f"{fruit}: {count}" for fruit, count in rows]
print("\n".join(lines))
Output
apples: 3 pears: 5
Test yourself
What does f"{3.14159:.2f}" produce?
3.13.143.1423.14159
Show answer
Answer: 3.14