python · level 2 · unit 3 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Three widths, three sides. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
print(f"[{'cat':>6}]")
print(f"[{'cat':<6}]")
print(f"[{42:^6}]")
your turn
Your turn. Print a league table.
Give each row a team name and its points. Then fill in the format specs: names left-aligned in 12 characters, points right-aligned in 4.
fix it
The receipt columns are wonky. Can you fix it?
- Which item name is longer than its column? Count its letters.
- Strawberries has 12 letters, but the width is 8, so it pushes its price out of line. A width only pads, it never cuts.
- Change <8 to <14 on line 3, then run.
nailed it
your tables line up like a receipt. :D
- A number in the format spec sets the width.
<aligns left,>aligns right and^centres.- Make each width wider than its longest value.
new words in your collection
- width
- padding
- align
This lesson isn’t saved. A free account remembers every lesson you finish.