I always keep googling Python f-string formatting options, so I finally decided to put everything I actually use into one place. And what better place than my own blog?
This is my personal cheatsheet: the stuff I reach for over and over when writing real code. It’s not exhaustive, because I don’t care about every edge case or obscure format. It’s just the 80/20 of f-string formatting: the things that save me time, make code more readable, and keep me from typing “python f-string format decimal” into Google for the hundredth time.
If you also find yourself constantly forgetting whether it’s :.2f or :,.2f or :2SQPDOIFHSQDOF, this might be useful to you too.
Numbers
We’re going to use these as examples:
n = 1234567x = 3.14159
Decimal int
f"{n:d}" → 1234567
Zero-padded width
f"{n:08d}" → 01234567
Thousands separator
Comma: f"{n:,}" → 1,234,567
Underscore: f"{n:_}" → 1_234_567
Hex / binary / octal
f"{42:x}" → 2a
f"{42:#x}" → 0x2a
f"{42:b}" → 101010
Fixed decimals
f"{x:.2f}" → 3.14
Scientific notation
f"{x:.3e}" → 3.142e+00
General format (auto picks fixed or sci)
f"{1000000:.3g}" → 1e+06
Percent
f"{0.1234:.1%}" → 12.3%
Width, Alignment, Padding
s = "hi"
Align text
Left: f"{s:<10}" → ‘hi ’
Right: f"{s:>10}" → ’ hi’
Center: f"{s:^10}" → ’ hi ‘
Fill character
f"{s:.<10}" → ‘hi…’
Sign handling
Always: f"{7:+d}" → +7
Space: f"{7: d}" → ’ 7’
Zero-pad after sign: f"{7:=+6d}" → +00007
Alternate form
f"{10:#b}" → 0b1010
f"{3.0:#.0f}" → 3. (forces decimal point)
Strings & Misc
Truncate string
f"{'abcdef':.5}" → ‘abcde’
Conversions
f"{obj!r}" → uses repr(obj)
f"{obj!s}" → uses str(obj)
f"{obj!a}" → ASCII-safe
Debug print
value = 42
f"{value=}" → “value=42”
Rounding (Banker’s Rounding)
Python’s formatting and round() both use round half to even (a.k.a. banker’s rounding):
round(2.5) # 2
round(3.5) # 4
f"{2.5:.0f}" # '2'
f"{3.5:.0f}" # '4'For exact decimal rounding (finance, money): use Decimal:
from decimal import Decimal, ROUND_HALF_EVEN
Decimal("2.675").quantize(Decimal("0.01"), rounding=ROUND_HALF_EVEN) # '2.68'Format Spec Syntax
[[fill]align][sign][#][0][width][grouping][.precision][type]align: < left, > right, ^ center, = pad after sign
sign: +, -, or (space)
grouping: , or _
types (common):
-
dint -
b/o/x/Xbinary/octal/hex -
ffixed-point -
e/Escientific -
g/Ggeneral -
%percentage -
sstring
My most-used combos
- Money-ish:
f"{x:,.2f}"→ 1,234.57 - Zero-padded IDs:
f"{n:08d}"→ 00001234 - Right-align columns:
f"{s:>12}" - Hex with prefix:
f"{n:#x}"→ 0x2a - Percent:
f"{p:.1%}"→ 12.3%
Valérian de Thézan de Gaussan