Code Reference

F-strings

Python · Reference cheat sheet

F-strings

Python · Reference cheat sheet


📋 Overview

Formatted string literals (f"..." / f'...') embed expressions inside \{\}. They are the preferred way to build strings in modern Python (3.6+). Use them for logging messages, paths, and readable interpolation—avoid for SQL/HTML without escaping.

🔧 Core concepts

FeatureSyntax
Basicf"Hello, \{name\}"
Expressionf"\{x + 1\}", f"\{obj.attr\}"
Format specf"\{value:.2f\}", f"\{n:04d\}"
Debug (3.8+)f"\{x=\}"x=42
Conversion!s str, !r repr, !a ascii
Nested quotesPrefer different quote styles or escapes
Multilinef"""..."""

Format mini-language: alignment (<^>), width, precision, types (d, f, x, %).

💡 Examples

Formatting numbers and dates:

from datetime import datetime

price = 19.5
n = 42
now = datetime(2026, 7, 10, 13, 30)

print(f"${price:.2f}")       # $19.50
print(f"{n:04d}")            # 0042
print(f"{now:%Y-%m-%d %H:%M}")

Debug and repr:

user = "Ada"
print(f"{user=}")            # user='Ada'
print(f"{user!r}")           # 'Ada'

Alignment and tables:

rows = [("id", "name"), (1, "Ada"), (2, "Bob")]
for a, b in rows:
    print(f"{a!s:>4} | {b:<10}")

Walrus in f-string (careful):

data = [1, 2, 3]
print(f"{(n := len(data))} items")  # 3 items

⚠️ Pitfalls

  • Backslashes inside \{\} expressions are limited; compute outside the braces if needed.
  • Nested f-strings and complex expressions hurt readability—extract variables.
  • Never build SQL/shell commands with raw f-strings; use parameterized APIs.
  • Mixing str.format / % / f-strings inconsistently makes style noisy.
  • Lazy logging: prefer logger.info("x=%s", x) over f"..." if the message may be skipped (minor; clarity often wins).

On this page