Sub topic 14
Formatting output with f-strings
This chapter assumes you can run Python scripts, call print(), and use strings, numbers, and the arithmetic operators from earlier chapters. It covers how to build readable output with f-strings and format specifiers.
What an f-string is
An f-string is a string literal with an f prefix. Python evaluates each expression inside {} and inserts the result as text. The expression can be a name, arithmetic, a method call, or any other expression.
name = "Ada"
total = 1234.5
print(f"{name}: {total:,.2f}")
print(f"{total=}")
print(f"{42:08b}")
print(f"{'left':<10}|{'right':>10}|")This prints:
Ada: 1,234.50
total=1234.5
00101010
left | right|Each replacement field has up to three parts: {expression!conversion:format_spec}. The conversion and the format spec are both optional.
The format specifier
The text after the colon is the format specifier. It tells Python how to turn the value into text. A common layout is [[fill]align][sign][0][width][,][.precision][type].
| Piece | Meaning | Example | Result |
|---|---|---|---|
| `.2f` | Fixed point, 2 decimals | `f"{3.14159:.2f}"` | `3.14` |
| `,` | Thousands separator | `f"{1234567:,}"` | `1,234,567` |
| `b` | Binary integer | `f"{5:b}"` | `101` |
| `08b` | Binary, zero-padded to width 8 | `f"{42:08b}"` | `00101010` |
| `<10` | Left-align in 10 characters | `f"{'hi':<10}"` | `hi ` |
| `>10` | Right-align in 10 characters | `f"{'hi':>10}"` | ` hi` |
| `.1%` | Percentage | `f"{0.256:.1%}"` | `25.6%` |
Strings align left by default and numbers align right. The .2f type rounds to two decimals. It does not change the value, only the text.
Self-documenting expressions
Adding = after an expression prints the expression text, an equals sign, and the value. This works in Python 3.8 and later and is handy for quick debugging.
price = 4.5
quantity = 3
print(f"{price * quantity=}")This prints price * quantity=13.5.
Building an aligned table
Width and alignment let you line up columns without manual spacing.
items = [("Tea", 3, 2.5), ("Coffee", 12, 3.75), ("Juice", 100, 4.0)]
print(f"{'Item':<8}{'Qty':>5}{'Price':>10}")
for item, qty, price in items:
print(f"{item:<8}{qty:>5}{price:>10,.2f}")This prints:
Item Qty Price
Tea 3 2.50
Coffee 12 3.75
Juice 100 4.00A width can itself come from a name by nesting a field: f"{value:>{width}}".
flowchart LR
A["Expression in braces"] --> B["Evaluate"]
B --> C["Apply format spec"]
C --> D["Insert text into string"]Common errors
- Quotes inside the braces. Before Python 3.12, you could not reuse the outer quote type inside a replacement field. Use the other kind:
f"{d['key']}". - Literal braces. Double them:
f"{{x}}"prints{x}. - Wrong type code.
f"{'text':.2f}"raisesValueError, becausefapplies to numbers only. - Forgetting the prefix.
"{name}"withoutfprints the braces unchanged. - Formatting for storage. A formatted value is a
str. Do arithmetic before formatting, not after.
Exercise
Given n = 1234567.891, write one f-string that prints it with thousands separators, two decimals, and right-aligned in a field 15 characters wide.
Show answer
print(f"{n:>15,.2f}") prints 1,234,567.89. The alignment and width come first, then the comma, then the precision and type.
Exercise
What does print(f"{{score}} = {score}") print when score = 9?
Show answer
It prints {score} = 9. The doubled braces are literal text, and the single-brace field is replaced by the value.