Sub topic 8
Width, alignment, precision, and number formats
This chapter assumes you can write basic f-strings, know the core types str, int, and float, and can run a Python script. Here you learn the format specification mini-language, the part after the colon in {value:spec}. It lets you line up columns, round numbers, and add separators without extra string handling.
The shape of a format spec
A replacement field has the form {expression:spec}. The spec follows this general pattern, and every part is optional:
[[fill]align][sign][#][0][width][,][.precision][type]The parts you will use most are alignment, width, the thousands separator, precision, and type.
| Part | Example | Meaning |
|---|---|---|
| align | `<`, `>`, `^` | Left, right, or center within the width |
| width | `10` | Minimum number of characters |
| `,` | `,` | Thousands separator |
| precision | `.2` | Decimal places for floats (with `f`) |
| type | `f`, `d`, `%` | How to present the value |
Width and alignment
Width sets the minimum size of the field. If the value is shorter, Python pads it. If the value is longer, Python does not cut it off.
Strings align left by default and numbers align right. Set the alignment explicitly when you want a table to look consistent.
price = 1234.5
qty = 3
print(f"{'Item':<10}{'Qty':>5}{'Total':>12}")
print(f"{'Widget':<10}{qty:>5}{price * qty:>12,.2f}")
print(f"{0.256:.1%}")The output is:
Item Qty Total
Widget 3 3,703.50
25.6%Read {price * qty:>12,.2f} from left to right. It means right-align in 12 characters, use a thousands separator, and show 2 decimal places as a fixed-point number.
Notice that 'Item' is quoted inside the f-string. Use a different quote type inside the braces than the one wrapping the string.
Fill characters
Put a character before the alignment symbol to pad with something other than spaces.
print(f"{'menu':*^20}")
print(f"{42:0>6}")
print(f"{42:06}")The first line centers menu between asterisks. The second pads with zeros on the left. The third shows the shortcut: a 0 before the width pads numbers with zeros.
Precision and number types
The meaning of .precision depends on the type.
- With
f, it is the number of digits after the decimal point. - With
sor no type on a string, it is the maximum number of characters. - With
%, the value is multiplied by 100 and shown with a percent sign.
pi = 3.14159265
print(f"{pi:.2f}")
print(f"{pi:10.3f}|")
print(f"{'truncate':.4}")
print(f"{1_000_000:,}")
print(f"{255:b} {255:x} {255:#X}")
print(f"{0.0000123:.2e}")Here b is binary, x is hexadecimal, # adds the 0x-style prefix, and e is scientific notation. The d type formats integers, and it is the default for int.
Common mistakes
- Precision on integers.
f"{5:.2f}"works, because Python converts to float. Butf"{5:.2d}"raisesValueError, sincedaccepts no precision. - Wrong type for the value.
f"{'text':d}"raisesValueError. Match the type letter to the value. - Expecting truncation. Width never shortens a value. Use precision on a string if you need a maximum length.
- Rounding surprises.
f"{2.675:.2f}"prints2.67, because the float is stored as a binary approximation slightly below 2.675. For exact decimal rounding, use thedecimalmodule.
Dynamic width
You can nest a replacement field inside the spec to take the width from a variable.
rows = [("Widget", 1234.5), ("Gadget", 99.0), ("Thingamajig", 5.25)]
width = max(len(name) for name, _ in rows)
for name, amount in rows:
print(f"{name:<{width}} {amount:>10,.2f}")The table now adapts to the longest name.
Exercise
What does f"{1234567.891:>14,.1f}" print, and why does the number not look cut off?
Show answer
It prints 1,234,567.9 (three spaces, then the number). The spec right-aligns in 14 characters, adds a thousands separator, and rounds to one decimal place. The result is 13 characters, so one space of padding is added on the left. Width only sets a minimum.
Exercise
Write an f-string that shows the float score = 0.8731 as a percentage with one decimal place, centered in 10 characters.
Show answer
f"{score:^10.1%}" gives 87.3% . The % type multiplies by 100, .1 keeps one decimal place, and ^10 centers the result in 10 characters.