Lesson 6 of 6 · Numbers, Strings and Operators · 2 min read · Updated

Formatting output with f-strings

Putting values inside text, and controlling decimals, commas, widths and alignment.

Put an f before the quotes and anything inside { } is worked out and dropped into the text. This is an f-string, and it is the way modern Python builds text.

python
name = "Meena"
marks = 87.456
print(f"{name} scored {marks}")
print(f"{name} scored {marks:.1f}")
print(f"Next year: {2024 + 1}")
print(f"{name.upper()} has {len(name)} letters")
Output
Meena scored 87.456
Meena scored 87.5
Next year: 2025
MEENA has 5 letters

Any expression works inside the braces — arithmetic, method calls, function calls. After a colon comes the format spec, which controls how the value looks: .1f means one decimal place.

Useful format specs

python
price = 1234567.891
print(f"{price:,.2f}")
print(f"{0.4567:.1%}")
print(f"{7:03d}")
print(f"[{'left':<10}]")
print(f"[{'right':>10}]")
print(f"[{'mid':^9}]")
Output
1,234,567.89
45.7%
007
[left      ]
[     right]
[   mid   ]
  • ,.2f — thousands separators and two decimals. Right for money.
  • .1% — multiply by 100 and add a percent sign.
  • 03d — a whole number padded with zeros to 3 digits.
  • <10, >10, ^9 — left, right or centre in a space that wide.

Printing a neat table

python
menu = [("Idli", 30), ("Dosa", 55), ("Pongal", 45)]
for dish, price in menu:
    print(f"{dish:<8}{price:>5}")
Output
Idli       30
Dosa       55
Pongal     45

Note

Write f"{total=}" while debugging and Python prints the name and the value, such as total=250. You may also meet two older styles in existing code: "{} is {}".format(a, b) and "%s is %d" % (a, b). They still work; f-strings are clearer.

What does f"{3.14159:.2f}" produce?

Try this now

  1. Print a shopping bill: item names left-aligned, prices right-aligned with two decimals, and a total line.
  2. Print the numbers 1 to 10 alongside their squares and cubes in three aligned columns.

Create a free account to save your progress, or sign in.