PythonMastery
reference 5 min read · lesson 7 of 16 in Reference

Python F-String & Format Spec Cheat Sheet

1 · The lesson

read

Quick 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]}
PartExampleMeaning
fill*, 0, Character used to pad
align< > ^ =Left / right / centre / pad after sign
sign+ - Show sign on numbers
##Alt form (0x, 0b, 0o prefix)
00Zero-pad numbers
width10Minimum field width
grouping, or _Thousands separator
.precision.3Decimals / max chars for strings
typef 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

SpecInputOutputUse
.2f3.141593.14Fixed-point, 2 decimals
.3e12345.61.235e+04Scientific
.0f3.74Round, no decimals
,10000001,000,000Thousands separator
_10000001_000_000Underscore separator
.1%0.0858.5%Percentage
:b101010Binary
:o1012Octal
:x255ffHex lowercase
:X255FFHex uppercase
:#x2550xffHex with prefix
:+d42+42Force 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 / SymptomCauseFix
SyntaxError: f-string expression part cannot include a backslashf"{'\n'}" (pre-3.12)Bind to var: nl = "\n"; f"{nl}"
SyntaxError: f-string: unmatched '{'Missing closing braceBalance braces; escape literal as {{ }}
ValueError: Unknown format code 'f' for object of type 'str'f"{name:.2f}" on a stringConvert: f"{float(name):.2f}"
Output is {x} literallyMissing f prefixUse f"...", not "..."
Curly braces vanishForgot to double themf"{{literal}}" -> {literal}

See Also

Practice this

on practicepython.in

Short exercises that run in your browser and tell you what your code actually did, not just whether a test passed.