Programming Search⌘K

Featureintro

Formatted String Literals

Also called f-string, f-strings, formatted string literal, string interpolation, f prefix, debug specifier, self-documenting expression.

An f-string has an f prefix and holds expressions in braces. Python evaluates each expression at run time and puts its formatted value in the string. A field can add =, a conversion and a format spec.

Language
Python

Synopsis

import math
name, count = "eels", 13
print(f"My hovercraft is full of {name}.")
print(f"{name!r} {count * 2} {math.pi:.3f}")
print(f"{count=} {name.upper()=}")
Output
My hovercraft is full of eels.
'eels' 26 3.142
count=13 name.upper()='EELS'

Each pair of braces holds an expression. A field can add a conversion such as !r, a format spec after :, or =.

Semantics

r1. "A formatted string literal or f-string is a string literal that is prefixed with ‘f’ or ‘F’. Unlike other string literals, f-strings do not have a constant value."1 "Replacement fields contain expressions which are evaluated at run time."1 PEP 498 says that "an f-string is really an expression evaluated at run time, not a constant value."4

r2. "Any doubled curly braces ({{ or }}) outside replacement fields are replaced with the corresponding single curly brace".1 Example: braces.

r3. "Each expression is evaluated in the context where the formatted string literal appears, in order from left to right. An empty expression is not allowed, and both lambda and assignment expressions := must be surrounded by explicit parentheses".1 Examples: order, empty-field.

r4. "Reusing the outer f-string quoting type inside a replacement field is permitted".1 "Backslashes are also allowed in replacement fields and are evaluated the same way as in any other context".1 PEP 701 lifts "some of the restrictions originally formulated in PEP 498".5 Example: nested-quotes.

r5. With a debug specifier =, "the resulting f-string will contain the expression’s source, the equal sign, and the value of the expression."2 "When a debug specifier but no format specifier is used, the default conversion instead uses repr()".2

r6. "By default, the value of a replacement field expression is converted to a string using str()".2 The conversions !s, !r and !a call str(), repr() and ascii().2 "If the replacement field includes a format specifier introduced by a colon (:), the specifier is passed to format() as the second argument."2

r7. "Top-level format specifiers may include nested replacement fields".1 Example: nested-spec.

r8. "Formatted string literals cannot be used as docstrings, even if they do not include expressions".1

Examples

items = 3
print(f"{{items}} = {items}")
print(f"{{{items}}}")
Output
{items} = 3
{3}

Two braces give one literal brace (rule r2).

data = {"x": 2}
words = ["a", "b", "c"]
print(f"value {data["x"]}")
print(f"list:\n{"\n".join(words)}")
Output
value 2
list:
a
b
c

The field uses the same double quotes as the f-string, and it holds a backslash (rule r4).

number = 14.3
width, precision = 10, 3
print(f"[{number:{width}.{precision}f}]")
print(f"[{number:<{width}}]")
Output
[    14.300]
[14.3      ]

The inner fields give the width and the precision (rule r7).

value = 14.3
print(f"{value=}")
print(f"{ value - 4 = }")
print(f"{value = :.1f}")
print(f"{'tea'=} {'tea'=!s}")
Output
value=14.3
 value - 4 = 10.3
value = 14.3
'tea'='tea' 'tea'=tea

The spaces around = stay in the result. With = alone, the value uses repr(), and !s changes that (rule r5).

Pitfalls

The expressions run when the f-string is evaluated, not later:

This code runs but gives a wrong answer on purpose.

name = "Ada"
greeting = f"Hello, {name}"
name = "Grace"
print(greeting)
Output
Hello, Ada

The f-string has a value at once (rule r1). To fill a pattern later, use str.format() or a function.

An empty field is a syntax error:

This code raises SyntaxError, on purpose.

print(f"value: {}")

An f-string is not a docstring:

def area():
    f"Return the area."
    return 1

print(area.__doc__)
Output
None

Comparison

Go has no string interpolation in the language. A program calls fmt.Sprintf, which "formats according to a format specifier and returns the resulting string."6 The values come after the format string, as with Python % formatting. A Python f-string puts each expression in its field (rule r1).

References

  1. The Python Language Reference, Python 3.15, 2.5.7. f-strings
  2. Built-in Types, Python 3.15 documentation, Formatted String Literals (f-strings); Debug specifier; Conversion specifier; Format specifier
  3. The Python Tutorial, 7. Input and Output, 7.1.1. Formatted String Literals
  4. PEP 498: Literal String Interpolation, Abstract
  5. PEP 701: Syntactic formalization of f-strings, Abstract
  6. Package fmt, Go standard library, func Sprintf

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source