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.

Example 1Try it yourself
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.

Example 2Try it yourself
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.

Example 3Try it yourself
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:

Example 4Try it yourself
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?

  1. 3.1
  2. 3.14
  3. 3.142
  4. 3.14159
Show answer

Answer: 3.14