Python Formatting a Report
A report lines up names and numbers in neat columns. Format specs inside f-strings set the width and the decimals.
Two places after the point
The spec .2f shows two decimals. The price 3.5 prints as 3.50.
price = 3.5
print(f"Price: {price:.2f}")Numbers lined up on the right
The spec >5 pushes each number right in five spaces. The ones column lines up.
print(f"{7:>5}")
print(f"{123:>5}")
print(f"{42:>5}")A name and a score in columns
The name takes ten spaces on the left. The score takes three spaces on the right.
name = "ada"
score = 88
print(f"{name:<10}{score:>3}")A comma in big numbers
The spec ,.2f groups the digits with commas. The total prints with two decimals.
total = 1234567.891
print(f"Total: {total:,.2f}")Example
items = [("Pencil", 2, 1.50), ("Notebook", 1, 4.25), ("Ruler", 3, 0.80)]
print(f"{'Item':<12}{'Qty':>4}{'Each':>8}{'Cost':>8}")
total = 0
for name, qty, price in items:
cost = qty * price
total = total + cost
print(f"{name:<12}{qty:>4}{price:>8.2f}{cost:>8.2f}")
print(f"{'Total':<12}{'':>4}{'':>8}{total:>8.2f}")Key points
- Report: rows of names and numbers lined up in columns
- Use f"{value:>8}" to push a number right inside eight spaces
- Use f"{name:<12}" to push a name left inside twelve spaces
- Use f"{price:.2f}" to show a price with two places after the point
- Use f"{total:,.2f}" to show a big total with commas and two decimals
- The width sits after the colon, and the decimals sit after the dot.
- A width too small for a value never cuts that value short.
In this example, the list holds three shop items with a count and a price. The header prints the four column names in their widths. The loop works out each line cost and adds it to the total. Each row prints the name on the left and the numbers on the right. The total of 9.65 proves the three line costs add up.
Note
Format specs change the look only, so the value itself stays the same.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does f"{3.14159:.2f}" print?