Python f-strings: Formatted String Literals
What you’ll learn
Section titled “What you’ll learn”- 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.formatand the%operator.
Summary
Section titled “Summary”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.
The problem it solves
Section titled “The problem it solves”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.
How it works
Section titled “How it works”Basic embedding
Section titled “Basic embedding”name = "Alice"age = 25print(f"Hello, {name}! You are {age} years old.")# Hello, Alice! You are 25 years old.
x, y = 10, 20print(f"The sum of {x} and {y} is {x + y}")# The sum of 10 and 20 is 30Any expression goes inside {}: method calls, indexing, arithmetic, and function calls.
Format specifiers
Section titled “Format specifiers”After a colon, the same mini-language as str.format applies:
price = 19.99print(f"Price: ${price:.2f}") # Price: $19.99
value = 1234567.89print(f"{value:,.2f}") # 1,234,567.89
print(f"{0.875:.1%}") # 87.5%print(f"{255:#x}") # 0xffprint(f"{42:08}") # 00000042Alignment
Section titled “Alignment”< 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***|Dates and times
Section titled “Dates and times”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:00print(f"{now:%B %d, %Y}") # January 15, 2025The {x=} debug specifier (3.8+)
Section titled “The {x=} debug specifier (3.8+)”count = 42print(f"{count=}")# count=42This prints the expression text and its value — handy for logging. You can add a format spec: f"{count=:>5}" yields count= 42.
Multiline f-strings
Section titled “Multiline f-strings”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.
Performance
Section titled “Performance”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 writef"{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.
Realistic example
Section titled “Realistic example”OrdersPortal formats an order summary with currency, a receipt with aligned columns, and a debug log line for a failed charge.
from datetime import datetimefrom 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'Production patterns
Section titled “Production patterns”- Use f-strings for all string interpolation in application code; reserve
str.formatfor 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 off"amount={amount}"— it is shorter and stays correct if you rename the variable. - For currency, format with
:,.2fand store values asDecimalto avoid float rounding. - For columnar output (receipts, tables), align with
<,>,^and a fixed width.
Common mistakes
Section titled “Common mistakes”- 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.formatwith explicit fields or a templating library. - Forgetting the
fprefix —"{x}"is a plain string that prints literally. - Using
%formatting orstr.formatwhere 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.
When to use it and when not to
Section titled “When to use it and when not to”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.formatwith fixed field names or a template engine. - You need localization or internationalization with translatable templates —
str.formator gettext-based templates are safer because the template is data, not code. - A placeholder must be reused across many calls with different values —
str.formatcan store the template once.
Compatibility
Section titled “Compatibility”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+.
Interview questions
Section titled “Interview questions”-
How does an f-string differ from
str.formatand 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.formattakes 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.formatis better for templates stored as data;%is legacy. -
What does
f"{value:,.2f}"produce, and what does the,mean? It formatsvalueas a fixed-point number with two decimals and thousands separators —1234567.891becomes"1,234,567.89". The,enables the thousands separator;.2fsets two decimal places. -
What does
{x=}do, and in which Python version was it added? It prints both the expression text and its value:f"{count=}"yieldscount=42. It was added in Python 3.8 and is useful for quick debug logging. -
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 aneval. They should usestr.formatwith a fixed, controlled field set —"Dear {name}, your order {order_id} ships {date}".format(name=..., order_id=..., date=...)— or a dedicated templating library likestring.Templateor Jinja2, which treat the template as data and substitute named placeholders without executing code. The template never runs as Python.
Key takeaways
Section titled “Key takeaways”- 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.formatand%, but they execute code — never build them from untrusted input. - Use
str.formator a template library for external, reusable, or localized templates.
Related pages
Section titled “Related pages”- 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