How do f-strings work in Python?
f-strings (formatted string literals) let you embed expressions directly in strings using curly braces the clearest and fastest string interpolation in Python.
Python
Overview
Introduced in Python 3.6, f-strings are the modern standard for string formatting. Prefix a string with `f` and put any Python expression in `{}`. They are faster than `%` formatting and `.format()`, and far more readable.
Key Points
- •Syntax: `f"text {expression} text"` any valid Python expression goes inside `{}`.
- •Supports format specs: `f"{value:.2f}"` for floats, `f"{n:,}"` for thousand-separators.
- •`f"{value!r}"` calls `repr()`, `f"{value!s}"` calls `str()`.
- •Python 3.12 added `f"{value=}"` for debug output: prints `value=42`.
- •Multi-line f-strings use a backslash continuation or triple quotes.
Examples
Basic embedding
pythonname = "Alice"
age = 30
print(f"Hello, {name}! You are {age} years old.")
# Hello, Alice! You are 30 years old.
# Expressions work too
print(f"Next year you'll be {age + 1}.")Format specifiers
pythonpi = 3.14159265
print(f"Pi is approximately {pi:.2f}") # Pi is approximately 3.14
print(f"Pi is approximately {pi:.4f}") # Pi is approximately 3.1416
price = 1234567.89
print(f"${price:,.2f}") # $1,234,567.89
name = "Bob"
print(f"{name:>10}") # right-align in 10-char field: " Bob"Debug output with = (Python 3.8+)
pythonx = 42
y = [1, 2, 3]
print(f"{x=}, {y=}")
# x=42, y=[1, 2, 3]The = suffix is incredibly useful during debugging no need to type the variable name twice.
Pro Tip
F-strings evaluate at runtime, so you can call methods, access attributes, or run any expression: `f"{user.name.upper()}"`, `f"{len(items)} items"`. But keep expressions simple complex logic in f-strings is hard to read and test.