Formatting output

Topic 2 of 2 in Working with text5 min readBeginnerFree course

Overview

print(total) might show 41.38749999999999. Your users want 41.39. Formatting turns raw values into readable output: the right number of decimals, separators in big numbers, percentages, and columns that line up. In Python, almost all of it is done with format specifiers inside f-strings.

The format specifier

After the value inside the braces, add a colon and a specification:

Python
price = 3.14159
f"{price}"          # '3.14159'
f"{price:.2f}"      # '3.14'

F-string format specifiers. f”{price:>10,.2f}” is made of: the value (price), a colon, the alignment (>), the width (10), the thousands separator (,), and the precision and type (.2f). Examples: f”{3.14159:.2f}” gives 3.14; f”{1234567:,}” gives 1,234,567; f”{0.256:.1%}” gives 25.6%; f”{‘tea’:<8}|” gives tea followed by five spaces then a bar; f”{‘tea’:>8}|” gives five spaces then tea; f”{‘tea’:^8}|” gives two spaces, tea, three spaces; f”{42:05d}” gives 00042; and f”{total=}” gives total=17.5.

The parts all come in a fixed order — [fill][align][width][,][.precision][type] — and every part is optional.

Numbers

Decimal places: .Nf

Python
f"{2 / 3:.2f}"        # '0.67'
f"{2 / 3:.4f}"        # '0.6667'
f"{5:.2f}"            # '5.00' — works on ints too
f"{41.38749:.2f}"     # '41.39'

.2f rounds for display; the variable keeps its full value.

Thousands separators

Python
f"{1234567:,}"         # '1,234,567'
f"{1234567.891:,.2f}"  # '1,234,567.89'
f"{1234567:_}"         # '1_234_567'

Percentages

% multiplies by 100 and adds a percent sign:

Python
f"{0.256:.1%}"        # '25.6%'
f"{0.075:.0%}"        # '8%'
f"{3 / 4:.0%}"        # '75%'

Integers and other types

Python
f"{42:d}"             # '42' — integer
f"{42:05d}"           # '00042' — zero-padded to 5 digits
f"{255:x}"            # 'ff' — hexadecimal
f"{5:b}"              # '101' — binary
f"{1500000:.2e}"      # '1.50e+06' — scientific notation
f"{-5:+d}", f"{5:+d}" # '-5', '+5' — always show the sign

Width and alignment

A width sets the minimum number of characters. Add < (left), > (right) or ^ (centre):

Python
f"{'tea':<8}|"        # 'tea     |'
f"{'tea':>8}|"        # '     tea|'
f"{'tea':^8}|"        # '  tea   |'

Defaults: text aligns left, numbers align right — which is usually what you want in a table. A value longer than the width is never cut; it just overflows.

Fill characters

Put a character before the alignment to fill with it instead of spaces:

Python
f"{'MENU':*^20}"      # '********MENU********'
f"{7:0>3}"            # '007'

Building tables

Combine widths to make columns line up:

Python
rows = [("Tea", 3.5), ("Cappuccino", 4.25), ("Cake", 12)]

print(f"{'Item':<12}{'Price':>8}")
print("-" * 20)
for item, price in rows:
    print(f"{item:<12}{price:>8.2f}")
Text
Item           Price
--------------------
Tea             3.50
Cappuccino      4.25
Cake           12.00

Format specifiers can even use variables, with nested braces: f"{item:<{width}}".

Dates

Date and time objects have their own codes (The standard library):

Python
from datetime import date
d = date(2026, 12, 4)
f"{d:%d %B %Y}"       # '04 December 2026'
f"{d:%Y-%m-%d}"       # '2026-12-04'

Debugging with =

Put = after an expression to print both the expression and its value:

Python
total = 17.5
count = 3
print(f"{total=}, {count=}")          # total=17.5, count=3
print(f"{total / count=:.2f}")        # total / count=5.83

This is one of the quickest debugging tools in Python.

!r: show the repr

!r displays a value as you’d write it in code — quotes included — which makes invisible spaces visible:

Python
name = " Asha "
print(f"[{name!r}]")      # [' Asha ']

Other formatting styles

You’ll see two older styles in existing code. They do the same job:

Python
"{:.2f}".format(3.14159)    # str.format()  → '3.14'
"%.2f" % 3.14159            # %-formatting  → '3.14'

Use f-strings in new code; they’re clearer and faster.

Most-used specifiers: .2f for money, , for big numbers, .1% for percentages, and </> with a width for columns.

Exercise

Print a receipt

Print a neatly aligned receipt for the items in the starter. Each line shows the item name left-aligned in 12 characters, the quantity right-aligned in 3, and the line total (price × quantity) right-aligned in 9 with 2 decimal places. Under a line of 24 dashes, print the subtotal, a 7.5% tax line and the total, aligned the same way, then the tax rate as a percentage with 1 decimal place and the order number padded with zeros to 6 digits. The output should match the comment exactly.

Python
items = [("Notebook", 3.5, 4), ("Coffee beans", 12.0, 1), ("Pen", 1.25, 10)]
tax_rate = 0.075
order_number = 427

# Expected output:
# Notebook      4    14.00
# Coffee beans  1    12.00
# Pen          10    12.50
# ------------------------
# Subtotal           38.50
# Tax                 2.89
# Total              41.39
# Tax rate: 7.5%
# Order #000427

Summary

  • Add a format specifier after a colon in an f-string: f"{price:.2f}" shows 2 decimal places.
  • , adds thousands separators, % shows a percentage, d formats integers, e uses scientific notation.
  • <, > and ^ align left, right and centre within a width: f"{name:<12}".
  • Zero padding (:05d) and fill characters (:*^10) control what fills the space.
  • f"{x=}" prints the expression and its value — handy for debugging.