Sub topic 8
Width, alignment, precision, and number formats
This chapter assumes you can write f-strings with simple replacement fields such as {name}, and that you know the basic types str, int, and float. Here you will learn what goes after the colon in {value:spec}. That part is called the format specification mini-language. The str.format() method and the built-in format() function use the same language.
The shape of a format spec
A format spec is a compact string with optional parts in a fixed order:
[[fill]align][sign]["z"]["#"]["0"][width][grouping]["." precision][type]Every part is optional, but the order is not. {n:,.2f} is valid. {n:.2f,} raises ValueError.
Width and alignment
width is the minimum number of characters the field takes. Shorter values are padded. Longer values are never cut off.
| Align | Meaning |
|---|---|
| `<` | Left-align |
| `>` | Right-align |
| `^` | Center |
| `=` | Put padding between the sign and the digits (numbers only) |
If you give no alignment, strings align left and numbers align right.
print(f"[{'abc':<8}]") # [abc ]
print(f"[{'abc':>8}]") # [ abc]
print(f"[{'abc':^8}]") # [ abc ]
print(f"[{'abc':*^9}]") # [***abc***]
print(f"[{42:6}]") # [ 42]
print(f"[{'ab':6}]") # [ab ]In {'abc':*^9} the character before the alignment symbol is the fill character. When centering cannot split the padding evenly, the extra character goes on the right, as in [ abc ].
Width counts code points, not screen columns. Text with East Asian wide characters or combining marks can look misaligned in a terminal even when the code is correct.
Signs and zero padding
The sign option controls when a sign appears.
| Sign | Meaning |
|---|---|
| `+` | Always show a sign |
| `-` | Show a sign only for negative numbers (the default) |
| space | A space for positive numbers, `-` for negative |
A 0 just before the width pads with zeros after the sign. It is shorthand for fill 0 with alignment =.
print(f"{5:+}") # +5
print(f"{5: }") # " 5"
print(f"{42:08}") # 00000042
print(f"{-42:08}") # -0000042
print(f"{-42:=8}") # - 42
print(f"{7:+05d}") # +0007Precision
The meaning of .precision depends on the type:
- For
f,e, and%, it is the number of digits after the decimal point. - For
g, it is the total number of significant digits. - For strings, it is the maximum length, so it truncates.
- For integers, it is not allowed.
print(f"{3.14159:.2f}") # 3.14
print(f"{'abcdefgh':.3}") # abc
print(f"{12345.6789:.2e}") # 1.23e+04
print(f"{0.125:.2f}") # 0.12
print(f"{2.675:.2f}") # 2.67The last two lines surprise many people. Python does not round half up. 0.125 is exactly representable in binary, so it is a true tie, and ties round to the even digit, giving 0.12. 2.675 is stored as slightly less than 2.675, so it rounds down to 2.67. If you need decimal rounding rules for money, use the decimal module.
Width and precision can come from variables. Put them in nested braces:
value = 3.14159
width = 10
prec = 3
print(f"[{value:{width}.{prec}f}]") # [ 3.142]Type codes
The last character selects how the value is presented.
| Type | Applies to | Result for the example |
|---|---|---|
| `d` | int | `f"{255:d}"` gives `255` |
| `b`, `o` | int | `f"{5:b}"` gives `101` |
| `x`, `X` | int | `f"{255:x}"` gives `ff` |
| `f` | float | `f"{2.5:f}"` gives `2.500000` |
| `e` | float | `f"{12345.6789:e}"` gives `1.234568e+04` |
| `g` | float | `f"{1234567.0:g}"` gives `1.23457e+06` |
| `%` | float | `f"{0.5:%}"` gives `50.000000%` |
| `s` | str | `f"{'hi':s}"` gives `hi` |
Without a type, int uses d, str uses s, and float uses a general format that behaves like g but always keeps at least one digit after the decimal point. A precision with no type on a float can therefore switch to exponent notation:
print(f"{1234.5678:.3}") # 1.23e+03
print(f"{1234.5678:.3f}") # 1234.568Give floats an explicit f when you want fixed decimals.
Using the wrong type for a value raises ValueError. The two common cases are f"{2.5:d}" ("Unknown format code 'd' for object of type 'float'") and f"{42:.2}" ("Precision not allowed in integer format specifier"). An int is accepted with f, e, g, and %, and is converted to float first.
Alternate form for integers
The # flag adds a prefix to binary, octal, and hex output. A zero-padded width includes the prefix.
print(f"{255:#x}") # 0xff
print(f"{255:#X}") # 0XFF
print(f"{5:08b}") # 00000101
print(f"{255:#010b}") # 0b11111111Grouping digits
A , inserts thousands separators. An _ does the same with underscores. Underscores also work with b, o, x, and X, where they group every four digits.
print(f"{1234567:,}") # 1,234,567
print(f"{1234567:_}") # 1_234_567
print(f"{1234567.891:,.2f}") # 1,234,567.89
print(f"{0.256:.1%}") # 25.6%The , option always uses commas, whatever the system locale. For locale-aware separators, use the n type or the locale module.
Putting it together: a table
Because width is a minimum and alignment is explicit, you can build aligned columns without any extra library.
rows = [("Widget", 3, 1234.5), ("Gadget", 12, 99.0), ("Thingamajig", 1, 5.25)]
print(f"{'Item':<12}{'Qty':>5}{'Price':>12}")
print("-" * 29)
for name, qty, price in rows:
print(f"{name:<12}{qty:>5}{price:>12,.2f}")This prints:
Item Qty Price
-----------------------------
Widget 3 1,234.50
Gadget 12 99.00
Thingamajig 1 5.25A name longer than 12 characters would push its row out of line, because width never truncates. If that matters, combine width and precision, as in {name:<12.12}.
Other objects and the `__format__` hook
The spec after the colon is not interpreted by f-strings. It is passed to the value's __format__ method. That is why datetime objects accept strftime codes:
from datetime import date
d = date(2026, 11, 26)
print(f"{d:%d %b %Y}") # 26 Nov 2026
print(f"{d:%Y-%m-%d}") # 2026-11-26Your own classes can define __format__ to accept custom specs. Classes that do not define it accept only an empty spec. f"{obj:>10}" on such an object raises TypeError. The fix is to convert first, for example f"{str(obj):>10}" or f"{obj!s:>10}".
Common errors
- Putting parts in the wrong order, such as
{n:.2f,}or{n:>,10}. Follow the order in the diagram. - Expecting width to truncate. Only precision on strings truncates.
- Expecting
0.125or2.675to round half up. - Forgetting that a colon inside the expression, such as a dictionary slice or a lambda, needs parentheses.
- Using
!rafter the spec. The conversion comes first:{x!r:>10}.
Exercise
What does print(f"{7:+05d}") print, and why does the sign come first?
Show answer
It prints +0007. The + flag always shows a sign. The 0 flag pads with zeros after the sign (the same as fill 0 with = alignment), so the total width of 5 is made of the sign followed by 0007.
Exercise
Write an f-string that shows the float ratio = 0.0734 as a percentage with one decimal place, right-aligned in a field 8 characters wide.
Show answer
f"{ratio:>8.1%}" gives 7.3%. The % type multiplies by 100 and appends a percent sign, .1 sets one decimal place, and >8 right-aligns the result in 8 characters.
Exercise
Why does f"{2.675:.2f}" print 2.67 rather than 2.68, and what would you use for exact decimal rounding?
Show answer
The float 2.675 is stored in binary as a value slightly below 2.675, so rounding to two places goes down. Use the decimal module with Decimal("2.675") and an explicit rounding mode when exact decimal behavior matters.