×

python · level 2 · unit 3 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Give each value a , and your columns line up.

A number in the format spec sets a width. {name:<10} adds until the name is 10 characters wide. The spaces go on the right, so the text sits on the left.

A sign chooses how to it: < for left, > for right and ^ for centre. Words usually go left and numbers right, so the decimal points stack up neatly.

Width and decimals combine: {price:>6.2f} is a price with two decimal places, right-aligned in 6 characters. Every row lines up like a till receipt.

items = [("Tea", 1.5), ("Flapjack", 2.25), ("Soup", 4)]
for name, price in items:
    print(f"{name:<10}{price:>6.2f}")
print(f"{'TOTAL':<10}{7.75:>6.2f}")

A width is a minimum: a value longer than its width is never cut short.