f-strings (Formatted String Literals)

Embed expressions directly inside a string literal — evaluated and formatted at the moment the literal runs.

                f"...{expression}..."
              

Purpose

An f-string is a string literal prefixed with f (or F) whose {...} sections contain expressions, evaluated when the literal runs and inserted into the resulting string.

Example

name = "Ada"
score = 91.5

print(f"{name} scored {score:.1f}%")
print(f"{name.upper()} — {'PASS' if score >= 60 else 'FAIL'}")
Ada scored 91.5%
ADA — PASS

Behavior notes

  • Anything inside {} is a real Python expression — a name, an attribute access, a function call, even a conditional expression — not a restricted mini-template language.
  • An optional : inside the braces introduces a format spec ({score:.1f}), the same mini-language str.format() and format() use — precision, width, alignment, thousands separators, and more.
  • Evaluation happens immediately, at the point the f-string literal itself executes — not lazily, and not re-evaluated later if the underlying variables change.
  • Since Python 3.12, an f-string can reuse the same quote character inside its expressions (f"{"nested"}") and can span multiple lines more flexibly; on 3.6–3.11 the expression portion cannot contain a backslash or the same quote character used to delimit the f-string itself.

Common mistakes

  • Assuming an f-string re-renders itself later, like a template bound to a data source. It doesn’t — it produces one fixed str at the moment it runs, exactly like any other expression.
  • Reaching for f"{value}" to convert something to text when str(value) says the same thing more directly and doesn’t invite an accidental format spec typo.

Implementation notes

f-string syntax and evaluation order are defined by the language grammar — identical across conforming implementations, though it’s a genuinely version-gated feature: unavailable before Python 3.6, and with real syntax restrictions before 3.12 as noted above.

Taught in these lessons

Related reference