Skip to content

← Pattern Matching, f-Strings and Newer Syntax step 2 of 23

Easy Primitives

Line Up Receipt Columns with f-Strings

You are printing a receipt in a terminal. Each line shows an item, a quantity and a price, and the columns have to line up:

--------Receipt--------
Coffee     2       3.50
Bagel      1       2.25

An f-string can do all of the padding. After the value, write a colon and a format spec, which says how to lay the value out:

name = "tea"
print(f"[{name:<6}]")      # [tea   ]   left-aligned in 6 characters
print(f"[{name:>6}]")      # [   tea]   right-aligned
print(f"[{name:*^7}]")     # [**tea**]  centred, padded with *
print(f"[{1234.5:,.2f}]")  # [1,234.50] commas and two decimal places

The width, such as 6, is a minimum. A longer value is never cut. To take the width from a variable, put the variable in its own braces, as in f"{name:<{width}}".

What to write

Fill in two functions:

  • heading(title, width) centres title in width characters and pads both sides with -. When the padding does not split evenly, the extra - goes on the right. The ^ alignment does this for you.
  • receipt_line(name, qty, price, width) returns three columns with one space between each pair:
    • name, left-aligned in width characters;
    • qty, right-aligned in 3 characters;
    • price, right-aligned in 10 characters, with a comma between thousands and two decimal places.

A value wider than its column keeps every character and pushes the rest of the line to the right. For example, receipt_line("Tea", 12, 1234.5, 6) gives "Tea 12 1,234.50".

What the driver checks

Keep solve as it is. It returns:

  • heading: the title centred across the whole line, which is width + 15 characters wide.
  • lines: one receipt line per item, in order. No items gives an empty list.