f-strings: format a receipt
f-strings: format a receipt
An f-string drops expressions straight into a string, and a : adds a
format spec for width, alignment, and precision:
name = "milk"
price = 2.5
f"{name}: ${price:.2f}" # 'milk: $2.50' β 2 decimal places
f"{name:<8}|" # 'milk |' β left-justify in width 8
f"{42:>5}" # ' 42' β right-justify in width 5
< left-aligns, > right-aligns, the number is the field width, and .2f
formats a float with two decimals.
Your task
Write receipt(items) where items is a list of (name, price) pairs.
Return a list of formatted lines, one per item, where each line is the name
left-justified to width 10, followed by the price formatted with a
leading $ and exactly two decimals, right-justified to width 8.
receipt([("milk", 2.5), ("bread", 3.0)])
# ['milk $2.50', 'bread $3.00']
receipt([("egg", 0.2)])
# ['egg $0.20']
(Each line is the 10-wide name plus the 8-wide price field, so it is 18 characters total.)
Hint: build each line with f"{name:<10}{'$' + format(price, '.2f'):>8}",
or format the $ amount into its own string first, then right-justify it.
Tests
- two items
- single item
- empty receipt
- line width is 18
- rounds to cents (hidden)
- large price (hidden)
Stuck? Ask for a spark
$ Console output will appear here.