← Practice
πŸ“– String formattingLearning path
Browsing as guestΒ·Sign in or create a free account to save progress and use tutor tools.
LessonΒ·difficulty 2/5Β·~15 min

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:

python
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.

python
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 the price as its own $0.00 string first (two decimals), then right-justify that to width 8 and place it after the name left-justified to width 10. Two format specs, one line per item.

Tests

  • two items
  • single item
  • empty receipt
  • line width is 18

✦ Stuck? Ask for a spark

Sign in or create a free account to use your monthly AI explainer allowance.

warming up
Loading editor…
Consolewaiting

$ Console output will appear here.

>_AI coach
Sign in or create a free account to chat with the tutor.