Skip to content

Python f-strings: Formatted String Literals

  • F-string syntax and how expressions inside {} are evaluated at runtime.
  • Format specifiers: precision, thousands separators, alignment, and percent.
  • Formatting dates and times inline with strftime-style codes.
  • The {x=} debug specifier for logging a variable name and value together.
  • Multiline f-strings and when f-strings beat str.format and the % operator.

F-strings (formatted string literals, Python 3.6+) prefix a string with f and embed Python expressions inside {}. The expression is evaluated at runtime and converted to a string, optionally formatted with a spec after a colon: f"{amount:.2f}" rounds to two decimals, f"{total:,}" adds thousands separators, f"{name:>10}" right-aligns. F-strings are evaluated at runtime, not compile time, but they are faster than str.format and the % operator because the format is resolved in one optimized step rather than a runtime method call that parses the template. The {x=} debug form (3.8+) prints both the variable name and its value.

Before f-strings, string interpolation meant the % operator ("Hello, %s" % name) or str.format ("Hello, {}".format(name)). The % operator is positional and error-prone with multiple values: you must match the order and count of placeholders to the tuple, and types must match the conversion codes. str.format is more flexible — named fields, attribute access, indexing — but verbose, and the field names are strings decoupled from the surrounding code, so renaming a variable does not update a "Hello, {name}" template.

F-strings put the expression directly in the string: f"Hello, {name}" reads naturally, the variable is right there, and any expression works, like f"Total: {sum(items):.2f}". The result is more readable, harder to get wrong, and faster.

name = "Alice"
age = 25
print(f"Hello, {name}! You are {age} years old.")
# Hello, Alice! You are 25 years old.
x, y = 10, 20
print(f"The sum of {x} and {y} is {x + y}")
# The sum of 10 and 20 is 30

Any expression goes inside {}: method calls, indexing, arithmetic, and function calls.

After a colon, the same mini-language as str.format applies:

price = 19.99
print(f"Price: ${price:.2f}") # Price: $19.99
value = 1234567.89
print(f"{value:,.2f}") # 1,234,567.89
print(f"{0.875:.1%}") # 87.5%
print(f"{255:#x}") # 0xff
print(f"{42:08}") # 00000042

< left, > right, ^ center, with a width. A fill character goes before the align symbol:

name = "Alice"
print(f"|{name:<10}|") # |Alice |
print(f"|{name:>10}|") # | Alice|
print(f"|{name:^10}|") # | Alice |
print(f"|{name:*^10}|") # |**Alice***|

Use strftime codes after the colon:

from datetime import datetime
now = datetime.now()
print(f"{now:%Y-%m-%d %H:%M:%S}") # 2025-01-15 14:30:00
print(f"{now:%B %d, %Y}") # January 15, 2025
count = 42
print(f"{count=}")
# count=42

This prints the expression text and its value — handy for logging. You can add a format spec: f"{count=:>5}" yields count= 42.

user = {"name": "Bob", "role": "admin"}
info = f"""
User Information:
Name: {user['name']}
Role: {user['role']}
"""

A single f before a triple-quoted string interpolates across all lines.

F-strings are evaluated at runtime but are faster than str.format and % because the format is compiled into a single optimized bytecode sequence rather than a runtime method call that parses the template. For tight loops that format many strings, f-strings are typically the fastest of the three.

Result shape and edge cases worth remembering:

  • No backslashes inside the {} part on Python 3.6–3.11 (you cannot write f"{value\n}"); use a temporary variable. Nested same-quote characters inside the expression were also restricted before 3.12. Python 3.12 (PEP 701) lifted both.
  • An f-string is evaluated at runtime; the expression runs every time the line executes, so side effects in the expression (function calls) do happen.
  • The {x=} form is a 3.8+ feature; on 3.6/3.7 it is a syntax error.

OrdersPortal formats an order summary with currency, a receipt with aligned columns, and a debug log line for a failed charge.

from datetime import datetime
from decimal import Decimal
class Order:
def __init__(self, order_id, customer, amount, currency="USD"):
self.order_id = order_id
self.customer = customer
self.amount = Decimal(str(amount))
self.currency = currency
def summary(self):
placed = datetime.now()
return (
f"Order {self.order_id} for {self.customer}: "
f"{self.currency} {self.amount:,.2f} "
f"(placed {placed:%Y-%m-%d %H:%M})"
)
def print_receipt(order_id, customer, items):
print(f"Receipt {order_id} — {customer}")
subtotal = Decimal("0")
for sku, qty, price in items:
line_total = qty * Decimal(str(price))
subtotal += line_total
print(f" {sku:<12} qty {qty:<3} @ ${Decimal(str(price)):>6,.2f} = ${line_total:>7,.2f}")
print(f" {'Subtotal':<28} ${subtotal:>7,.2f}")
print_receipt("ORD-1001", "Acme Corp", [("WIDGET-01", 2, "9.99"), ("SHIPPING", 1, "5.50")])
# Receipt ORD-1001 — Acme Corp
# WIDGET-01 qty 2 @ $ 9.99 = $ 19.98
# SHIPPING qty 1 @ $ 5.50 = $ 5.50
# Subtotal $ 25.48
order = Order("ORD-1001", "Acme Corp", 1999.50)
print(order.summary())
# Order ORD-1001 for Acme Corp: USD 1,999.50 (placed 2025-01-15 14:30)

Debug logging a failed charge:

amount = Decimal("199.50")
status = "declined"
print(f"charge failed: {amount=:,.2f} {status=}")
# charge failed: amount=199.50 status='declined'
  • Use f-strings for all string interpolation in application code; reserve str.format for templates stored as data (config files, internationalization) where the template is not literal in the source.
  • Prefer the {x=} debug form in log statements instead of f"amount={amount}" — it is shorter and stays correct if you rename the variable.
  • For currency, format with :,.2f and store values as Decimal to avoid float rounding.
  • For columnar output (receipts, tables), align with <, >, ^ and a fixed width.
  • Using backslashes or nested same-quotes inside {} on Python 3.6–3.11 — extract to a variable or upgrade to 3.12+.
  • Treating f-strings as safe for user-supplied templates — f-strings evaluate code, so never build an f-string from untrusted input; use str.format with explicit fields or a templating library.
  • Forgetting the f prefix — "{x}" is a plain string that prints literally.
  • Using % formatting or str.format where an f-string is clearer — modern Python prefers f-strings for inline interpolation.
  • Embedding expensive or side-effecting calls in f-strings used in hot loops — the expression runs every iteration.

Use f-strings when:

  • Interpolating variables and expressions into strings in source code.
  • Formatting numbers, dates, and aligned output.
  • Quick debug logging with {x=}.

Avoid f-strings when:

  • The template comes from external or untrusted data — f-strings would execute code; use str.format with fixed field names or a template engine.
  • You need localization or internationalization with translatable templates — str.format or gettext-based templates are safer because the template is data, not code.
  • A placeholder must be reused across many calls with different values — str.format can store the template once.

F-strings arrived in Python 3.6 (PEP 498). The {x=} debug form was added in Python 3.8. Backslashes and nested same-quotes inside expressions were disallowed until Python 3.12, when PEP 701 lifted both restrictions. Everything shown here runs on 3.9 through 3.14, except backslash or nested-same-quote expressions which require 3.12+.

  1. How does an f-string differ from str.format and the % operator? An f-string embeds expressions directly: f"{x:.2f}" puts the variable and its format inline, evaluated at runtime in one optimized step. str.format takes a template with named or positional fields filled in by a method call; % uses C-style conversion codes with a tuple. F-strings are the most readable and typically the fastest; str.format is better for templates stored as data; % is legacy.

  2. What does f"{value:,.2f}" produce, and what does the , mean? It formats value as a fixed-point number with two decimals and thousands separators — 1234567.891 becomes "1,234,567.89". The , enables the thousands separator; .2f sets two decimal places.

  3. What does {x=} do, and in which Python version was it added? It prints both the expression text and its value: f"{count=}" yields count=42. It was added in Python 3.8 and is useful for quick debug logging.

  4. Senior scenario: a team is building a templated email feature and a junior dev proposes loading f"Dear {name}, your order {order_id} ships {date}" from a config file. Why is that unsafe, and what should they use instead? F-strings are evaluated as Python expressions, so a template built from config or user input would execute arbitrary code embedded in it — an f-string built from untrusted text is effectively an eval. They should use str.format with a fixed, controlled field set — "Dear {name}, your order {order_id} ships {date}".format(name=..., order_id=..., date=...) — or a dedicated templating library like string.Template or Jinja2, which treat the template as data and substitute named placeholders without executing code. The template never runs as Python.

  • F-strings embed expressions directly and are the modern, readable default for interpolation.
  • Format specifiers after : handle precision, thousands separators, alignment, percent, and dates.
  • {x=} (3.8+) logs a variable’s name and value together.
  • F-strings are faster than str.format and %, but they execute code — never build them from untrusted input.
  • Use str.format or a template library for external, reusable, or localized templates.
  • walrus operator — inline assignment often paired with f-strings in loops
  • Type hints — annotating functions that return formatted strings
  • Magic methods — __format__ and __str__ that f-strings call
  • enumerate — numbered output that f-strings format