Syntax Cache
BlogMethodFeaturesHow It WorksBuild a Game
  1. Home
  2. Cheat Sheets
  3. Python
  4. Python f-strings Cheat Sheet
PythonCheat Sheet

Python f-strings Cheat Sheet

Quick-reference for f-string formatting syntax. Each section includes copy-ready snippets with inline output comments.

On this page
  1. 1Basic Interpolation
  2. 2Expressions Inside f-strings
  3. 3Format Specs: Padding and Alignment
  4. 4Number Formatting
  5. 5Date and Time Formatting
  6. 6Multiline f-strings
  7. 7Conversion Flags: !r, !s, !a
  8. 8Debug Format: f"{var=}" (Python 3.8+)
  9. 9Nested Quotes and Advanced Tricks
Basic InterpolationExpressions Inside f-stringsFormat Specs: Padding and AlignmentNumber FormattingDate and Time FormattingMultiline f-stringsConversion Flags: !r, !s, !aDebug Format: f"{var=}" (Python 3.8+)Nested Quotes and Advanced Tricks

Basic Interpolation

f-strings (Python 3.6+) embed expressions directly in string literals. Prefix the string with f or F.

Variables in braces
name = 'Alice'
age = 30
f'{name} is {age} years old'   # => 'Alice is 30 years old'
Expressions in braces
f'{2 + 3}'          # => '5'
f'{"hello".upper()}'  # => 'HELLO'
Literal braces (escape with doubling)
f'{{'   # => '{'
f'}}'   # => '}'
f'{{{42}}}'   # => '{42}'

Expressions Inside f-strings

Function calls
items = ['a', 'b', 'c']
f'{len(items)} items: {", ".join(items)}'
# => '3 items: a, b, c'
Ternary expression
x = 42
f'{"even" if x % 2 == 0 else "odd"}'   # => 'even'
Dictionary access
user = {'name': 'Bob', 'age': 25}
f'{user["name"]} is {user["age"]}'   # => 'Bob is 25'
Object attributes
from datetime import date
today = date.today()
f'{today.year}-{today.month:02d}-{today.day:02d}'
# => '2026-02-22'

Format Specs: Padding and Alignment

After the colon inside braces: f"{value:[[fill]align][width]}".

Right-align (>), left-align (<), center (^)
f"{'hi':>10}"    # => '        hi'
f"{'hi':<10}"    # => 'hi        '
f"{'hi':^10}"    # => '    hi    '
Custom fill character
f"{'hi':_>10}"   # => '________hi'
f"{'hi':*^10}"   # => '****hi****'
f"{'hi':.<10}"   # => 'hi........'
Zero-pad numbers
n = 42
f'{n:05d}'   # => '00042'
f'{n:08b}'   # => '00101010'  (binary)

Number Formatting

Precision, thousands separators, sign, and type specifiers.

Decimal places
pi = 3.14159
f'{pi:.2f}'    # => '3.14'
f'{pi:.4f}'    # => '3.1416'
f'{pi:.0f}'    # => '3'
Thousands separator
n = 1234567
f'{n:,}'     # => '1,234,567'
f'{n:_}'     # => '1_234_567'
Percentage
ratio = 0.856
f'{ratio:.1%}'   # => '85.6%'
f'{ratio:.0%}'   # => '86%'
Sign display
f'{42:+d}'    # => '+42'
f'{-42:+d}'   # => '-42'
f'{42: d}'    # => ' 42'   (space for positive)
Hex, octal, binary
n = 255
f'{n:x}'    # => 'ff'
f'{n:#x}'   # => '0xff'
f'{n:o}'    # => '377'
f'{n:b}'    # => '11111111'
Width + precision combined
f'{3.14159:10.2f}'    # => '      3.14'
f'{3.14159:010.2f}'   # => '0000003.14'

Date and Time Formatting

f-strings support strftime directives directly in the format spec.

Common date formats
from datetime import datetime
now = datetime(2026, 2, 22, 14, 30, 0)
f'{now:%Y-%m-%d}'          # => '2026-02-22'
f'{now:%B %d, %Y}'         # => 'February 22, 2026'
f'{now:%I:%M %p}'          # => '02:30 PM'
ISO format and weekday
f'{now:%Y-%m-%dT%H:%M:%S}'   # => '2026-02-22T14:30:00'
f'{now:%A}'                  # => 'Sunday'
f'{now:%a %b %d}'            # => 'Sun Feb 22'

Multiline f-strings

Parentheses for implicit concatenation
name = 'Alice'
count = 3
total = 29.99
msg = (
    f'Hello {name}, '
    f'you have {count} items '
    f'worth ${total:.2f}'
)
msg   # => 'Hello Alice, you have 3 items worth $29.99'

Each line is a separate f-string. Python concatenates them at compile time.

Triple-quoted f-string
report = f"""
Name:  {name}
Items: {count}
Total: ${total:.2f}
"""

Conversion Flags: !r, !s, !a

Apply repr(), str(), or ascii() to a value before formatting.

!r for repr (shows quotes)
name = 'Alice'
f'{name!r}'    # => "'Alice'"
f'{name}'      # => 'Alice'
!s for str (explicit)
n = 42
f'{n!s}'   # => '42'  (same as str(42))
!a for ascii (escapes non-ASCII)
text = 'caf\u00e9'
f'{text!a}'   # => "'caf\\xe9'"
!r in debugging
value = '  hello  '
f'Input: {value!r}'   # => "Input: '  hello  '"

!r is invaluable for debugging: it shows whitespace, quotes, and escape characters.

Debug Format: f"{var=}" (Python 3.8+)

The = specifier prints both the expression and its value. Great for quick debugging.

Basic debug output
x = 42
f'{x=}'       # => 'x=42'
f'{x = }'     # => 'x = 42'  (spaces preserved)
With expressions
x = 10
f'{x * 2 = }'    # => 'x * 2 = 20'
f'{x + 1 = }'    # => 'x + 1 = 11'
With format spec
price = 19.99
f'{price = :.2f}'   # => 'price = 19.99'
With !r conversion
name = 'Alice'
f'{name = !r}'   # => "name = 'Alice'"

Nested Quotes and Advanced Tricks

Mix quote types
key = 'name'
d = {'name': 'Alice'}
f"{d['name']}"    # => 'Alice'  (single inside double)
Nested f-strings (Python 3.12+)
items = ['a', 'b', 'c']
f"items: {', '.join(f'[{x}]' for x in items)}"
# => 'items: [a], [b], [c]'
Dynamic format spec
width = 15
align = '^'
f"{'centered':{align}{width}}"   # => '   centered   '
Lambda in f-string (needs parens)
f'{(lambda x: x**2)(5)}'   # => '25'

Wrap lambdas in parentheses to avoid syntax errors from the colon.

Learn Python in Depth
Python Collections Practice →Python Loops Practice →
Warm-up1 / 2

Can you write this from memory?

Write an expression that splits `item` by commas into a list of strings

See Also
String Methods →Error Handling →

Start Practicing Python

Free daily exercises with spaced repetition. No credit card required.

← Back to Python Syntax Practice
Syntax Cache

Build syntax muscle memory with spaced repetition.

Product

  • Pricing
  • Our Method
  • Daily Practice
  • Design Patterns
  • Interview Prep

Resources

  • Blog
  • Compare
  • Cheat Sheets
  • Vibe Coding
  • Muscle Memory

Languages

  • Python
  • JavaScript
  • TypeScript
  • Rust
  • SQL
  • GDScript

Legal

  • Terms
  • Privacy
  • Contact

© 2026 Syntax Cache

Cancel anytime in 2 clicks. Keep access until the end of your billing period.

No refunds for partial billing periods.