F-strings (f"Hello, {name}!", Python 3.6+) are the fastest, cleanest, and recommended default because they evaluate expressions directly inline at runtime; str.format() ("Hello, {}!".format(name)) is best when the template string must be defined separately from its variables (such as translation tables, config files, or reusable templates); and % formatting ("Hello, %s!" % name) is legacy C-style formatting retained mainly for backward compatibility and standard logging calls (where lazy argument interpolation avoids formatting strings when a log level is disabled).
Basic Example
item = "Notebook"
qty = 3
price = 4.5
# 1. Recommended (f-string — Python 3.6+, inline expressions & fastest execution):
print(f"{qty}x {item}: ${qty * price:.2f}")
# Output: 3x Notebook: $13.50
# 2. `.format()` — Best when template string is stored/loaded separately from values:
TEMPLATE = "{qty}x {item}: ${total:.2f}"
print(TEMPLATE.format(qty=qty, item=item, total=qty * price))
# Output: 3x Notebook: $13.50
# 3. `%` operator — Legacy C-style formatting (still standard in `logging.info(...)`):
print("%dx %s: $%.2f" % (qty, item, qty * price))
# Output: 3x Notebook: $13.50
Key Details & Edge Cases
- Tuple trap with the
%operator (TypeError: not all arguments converted):- When formatting a single variable with
%, passing atupledirectly—"%s" (1, 2)—interprets(1, 2)as two positional arguments instead of one tuple object, raisingTypeError. You must wrap single tuples in an extra 1-tuple:"%s" ((1, 2),). Neither f-strings (f"{(1, 2)}") nor.format()("{}".format((1, 2))) suffers from this bug.
- When formatting a single variable with
- Debugging expressions effortlessly with f-strings (
=specifier, Python 3.8+):- Appending
=inside an f-string placeholder prints both the source expression and itsrepr()value automatically:x, y = 10, 25 print(f"{x=}, {x + y=:.1f}") # Output: x=10, x + y=35.0
- Appending
- Nested quotes and multi-line expressions inside f-strings (Python 3.12+ vs. 3.6–3.11):
- In Python 3.12+, f-strings allow reusing the same quote type inside expressions (
f"User: {user["name"]}"), nesting f-strings arbitrarily deep, and embedding backslashes (\n) or comments inside—all of which raisedSyntaxErrorin Python 3.6–3.11.
- In Python 3.12+, f-strings allow reusing the same quote type inside expressions (
- Security risk with untrusted user templates (
str.format()/ f-strings vs.string.Template):- Never pass an untrusted user-supplied string into
.format(**data)oreval(f"...")—an attacker can traverse object attributes ("{0.__class__.__mro__}".format(x)) to leak secrets or global namespaces. Usestring.Template("$name").safe_substitute(data)when end users supply the template string.
- Never pass an untrusted user-supplied string into
- Why
loggingstill prefers%formatting over f-strings:- Writing
logger.debug(f"Payload: {expensive_serialize(data)}")evaluatesexpensive_serialize(data)unconditionally even whenDEBUGlogging is turned off, whereaslogger.debug("Payload: %s", data)defers string formatting until the log record is actually emitted.
- Writing
Comparison of %, .format(), and f-Strings in Python
| Feature | % Formatting (Legacy) |
str.format() |
f-Strings (f"...") (Recommended) |
|---|---|---|---|
| Python Version Support | All versions (Python 2 & 3) | Python 2.6+ and all Python 3 | Python 3.6+ (expanded grammar in 3.12+) |
| Runtime Speed | Moderate | Slowest (method lookup + arg parsing) | Fastest (compiled directly to BUILD_STRING bytecode) |
Inline Expressions ({a + b}, {fn(x)}) |
No (must precompute on right side) | No (only attribute/index lookup like {obj.x}) |
Yes (any valid Python expression inline) |
| Deferred / External Templates | Yes (tmpl % args) |
Yes (tmpl.format(**kwargs)) |
No (evaluated immediately at definition site) |
| Tuple Formatting Edge Case | Fails on unnested tuples ("%s" (1, 2)) |
Safe ("{}".format((1, 2))) |
Safe (f"{(1, 2)}") |
| Best Used When | Standard logging calls (logger.info("%s", x)) or maintaining legacy Python 2/3 codebases. |
Reusable templates loaded from config files, localization strings, or databases. | Default string interpolation, formatting numbers/dates, and inline debug output (f"{x=}"). |
You must log in or register to comment.
