20 min read
Formatted Output
Use f-strings to build neat messages, show money to two decimal places with thousands separators, and line up a receipt.
f-strings
An f-stringPython
item = "Red rice"kilos = 5price = 280print(f"{kilos} kg of {item} costs LKR {kilos * price}")Expected output
5 kg of Red rice costs LKR 1400
Put f before the opening quote, then write variables or calculations inside { }. Python replaces each {…} with its value. f-strings are the clearest way to build output.
Format Codes
| Useful format codes (after a colon inside { }) | |||
|---|---|---|---|
A Neat Receipt
receipt.pyPython
print("PERERA CORNER MART")print("-" * 30)print(f"{'Red rice (5 kg)':<20}{1400:>10,.2f}")print(f"{'Dhal (2 kg)':<20}{905:>10,.2f}")print(f"{'Bread':<20}{120:>10,.2f}")print("-" * 30)print(f"{'TOTAL':<20}{2425:>10,.2f}")Expected output
PERERA CORNER MART ------------------------------ Red rice (5 kg) 1,400.00 Dhal (2 kg) 905.00 Bread 120.00 ------------------------------ TOTAL 2,425.00
"-" * 30 repeats the dash 30 times. <20 puts each item name in a 20-character column; >10,.2f puts the price right-aligned in 10 characters, with commas and 2 decimal places — so the numbers line up.
Other Ways You May See
Three ways to combine text and numbers
| Method | Example |
|---|---|
| Commas in print() | print("Total:", total) |
| Joining with + (numbers must be converted) | print("Total: " + str(total)) |
| f-string (recommended) | print(f"Total: {total:,.2f}") |
Practice
total = 12345.6. Which prints LKR 12,345.60?
More lessons in Python Programming · Next: if and else · Previous: Input and Type Conversion
