What is the difference between %, .format(), and f-strings in Python string formatting? | A1Lab@MZeeshanM to PythonEnglish • 2 days ago

What is the difference between %, .format(), and f-strings in Python string formatting?

message-square
0

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 a tuple directly—"%s" % (1, 2)—interprets (1, 2) as two positional arguments instead of one tuple object, raising TypeError. 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.
  • Debugging expressions effortlessly with f-strings (= specifier, Python 3.8+):
    • Appending = inside an f-string placeholder prints both the source expression and its repr() value automatically:
      x, y = 10, 25
      print(f"{x=}, {x + y=:.1f}")
      # Output: x=10, x + y=35.0
      
  • 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 raised SyntaxError in Python 3.6–3.11.
  • Security risk with untrusted user templates (str.format() / f-strings vs. string.Template):
    • Never pass an untrusted user-supplied string into .format(**data) or eval(f"...")—an attacker can traverse object attributes ("{0.__class__.__mro__}".format(x)) to leak secrets or global namespaces. Use string.Template("$name").safe_substitute(data) when end users supply the template string.
  • Why logging still prefers % formatting over f-strings:
    • Writing logger.debug(f"Payload: {expensive_serialize(data)}") evaluates expensive_serialize(data) unconditionally even when DEBUG logging is turned off, whereas logger.debug("Payload: %s", data) defers string formatting until the log record is actually emitted.

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=}").