reference
5 min read
·
lesson 7 of 16 in Reference
Python F-String & Format Spec Cheat Sheet
1 · The lesson
readQuick reference for f-strings, format specifiers, and the mini-language. For the full tutorial see F-Strings.
1. Basic Interpolation
python
name = "Hedy" x, y = 3, 4 print(f"Hi {name}") # variable print(f"Sum = {x + y}") # expression print(f"Upper: {name.upper()}") # method call print(f"Char: {name[0]}") # subscript class U: pass u = U(); u.name = "Ada" print(f"User: {u.name}") # attribute
2. Format Spec Anatomy
python
{value:[fill][align][sign][#][0][width][grouping][.precision][type]}| Part | Example | Meaning |
|---|---|---|
fill | *, 0, | Character used to pad |
align | < > ^ = | Left / right / centre / pad after sign |
sign | + - | Show sign on numbers |
# | # | Alt form (0x, 0b, 0o prefix) |
0 | 0 | Zero-pad numbers |
width | 10 | Minimum field width |
grouping | , or _ | Thousands separator |
.precision | .3 | Decimals / max chars for strings |
type | f d e x % | Presentation type |
3. Width & Alignment
python
s = "py" print(f"[{s:<8}]") # [py ] left print(f"[{s:>8}]") # [ py] right print(f"[{s:^8}]") # [ py ] centre print(f"[{s:*^8}]") # [***py***] custom fill print(f"[{-42:=+8}]")# [- 42] pad after sign
4. Numeric Types
| Spec | Input | Output | Use |
|---|---|---|---|
.2f | 3.14159 | 3.14 | Fixed-point, 2 decimals |
.3e | 12345.6 | 1.235e+04 | Scientific |
.0f | 3.7 | 4 | Round, no decimals |
, | 1000000 | 1,000,000 | Thousands separator |
_ | 1000000 | 1_000_000 | Underscore separator |
.1% | 0.085 | 8.5% | Percentage |
:b | 10 | 1010 | Binary |
:o | 10 | 12 | Octal |
:x | 255 | ff | Hex lowercase |
:X | 255 | FF | Hex uppercase |
:#x | 255 | 0xff | Hex with prefix |
:+d | 42 | +42 | Force sign |
5. Zero-Padding Numbers
python
print(f"{7:05d}") # 00007 print(f"{3.14:08.2f}") # 00003.14 print(f"{255:#010x}") # 0x000000ff
6. Datetime Formatting
python
from datetime import datetime now = datetime(2026, 5, 14, 9, 30) print(f"{now:%Y-%m-%d}") # 2026-05-14 print(f"{now:%d %b %Y %H:%M}") # 14 May 2026 09:30 print(f"{now:%A, %I:%M %p}") # Thursday, 09:30 AM
See Datetime cheat for the full directive table.
7. Debug Syntax (3.8+)
python
x = 42 user = type("U", (), {"name": "Ada"})() print(f"{x=}") # x=42 print(f"{x*2=}") # x*2=84 print(f"{user.name=:>20}") # user.name= Ada
8. Nested Braces
Width and precision can be expressions:
python
width, prec = 10, 3 pi = 3.14159265 print(f"{pi:{width}.{prec}f}") # " 3.142" print(f"{'hi':{'*'}^{width}}") # "****hi****"
9. Multi-line F-Strings
python
name, score = "Hedy", 97 report = f""" User: {name} Score: {score:>5}/100 Grade: {'A' if score >= 90 else 'B'} """
10. When to Use .format() Instead
Use str.format(**dict) when the template is reusable or comes from outside the source file (config, i18n):
python
tmpl = "Hi {name}, you have {n} messages." print(tmpl.format(name="Hedy", n=3)) print(tmpl.format(**{"name": "Ada", "n": 7}))
F-strings cannot template a string that lives in a variable.
Common Patterns
python
# Right-align dollar amount in a 12-wide column print(f"{'TOTAL':<20}${1234.5:>10,.2f}") # TOTAL $ 1,234.50 # Pad ID with leading zeros print(f"USR-{42:06d}") # USR-000042 # Truncate float without rounding noise print(f"{3.14159:.2f}") # 3.14 # Percentage from ratio print(f"{17/200:.1%}") # 8.5% # Scientific notation print(f"{6.022e23:.3e}") # 6.022e+23 # Aligned table row for name, val in [("alpha", 1.5), ("beta", 22.0)]: print(f"{name:<10}{val:>8.2f}")
Common Errors
| Error / Symptom | Cause | Fix |
|---|---|---|
SyntaxError: f-string expression part cannot include a backslash | f"{'\n'}" (pre-3.12) | Bind to var: nl = "\n"; f"{nl}" |
SyntaxError: f-string: unmatched '{' | Missing closing brace | Balance braces; escape literal as {{ }} |
ValueError: Unknown format code 'f' for object of type 'str' | f"{name:.2f}" on a string | Convert: f"{float(name):.2f}" |
Output is {x} literally | Missing f prefix | Use f"...", not "..." |
| Curly braces vanish | Forgot to double them | f"{{literal}}" -> {literal} |
See Also
Practice this
on practicepython.inShort exercises that run in your browser and tell you what your code actually did, not just whether a test passed.