Format Specs
In an f-string, you can put a colon after the value inside the braces. The text after the colon is a format spec. It tells Python how to show the value, for example how wide it should be or how many decimal places to use.
| Format | Effect |
|---|---|
<8 | Left-align in 8 spaces |
>8 | Right-align in 8 spaces |
^8 | Center in 8 spaces |
.2f | Show two decimal places |
05d | Add zeros in front of a whole number to make it 5 wide |
, | Add a comma between thousands |
item = "Book"
quantity = 4
total = 1248.5
print(f"{item:<8}{quantity:>3}")
print(f"Total: {total:>10,.2f}")
Output:
Book 4
Total: 1,248.50
<8 makes room for 8 characters and puts Book on the left. Spaces fill the rest. >3 makes room for 3 characters and puts the quantity on the right. The last spec, >10,.2f, combines several rules. It right-aligns the number in 10 characters, adds a comma between thousands, and shows two decimal places.
Formatting only changes how the number looks when you print it. It rounds the number for display. It does not fix the small errors that float math can have.
In the exercise, format the lines of a receipt.