f-string improvements in Python 3.12
suggest changef-strings arrived in Python 3.6 (see Format literals f-string for the basics). The first version was parsed by a separate, hand-written parser inside the tokenizer, and that parser had rules you could trip over:
- you couldn't use the f-string's own quote character inside
{...} - the expression part couldn't contain a backslash
- the expression part couldn't contain a
#comment - a replacement field could only span several lines inside a triple-quoted f-string
- nesting was limited by the four kinds of quotes (
',",''',""")
Python 3.12 removed all of these (PEP 701). f-strings are now part of the regular grammar, and the expression inside {...} can be any Python expression that would be valid in parentheses.
This article covers:
- what you can write in Python 3.12+ that was a
SyntaxErrorbefore - the
{expr=}self-documenting specifier from Python 3.8, and how it combines with!r,!sand format specs - the better error messages and the new tokenizer output
- what still needs parentheses, and the compatibility cost of the new syntax
Examples were run with Python 3.13.15 (for 3.12+ behaviour) and Python 3.10.11 (for the old behaviour), using py -3.13 and py -3.10 on Windows. Paths in tracebacks are shortened to the file name.
Reusing the same quotes
Before 3.12, the f-string ended at the first quote that matched the opening one, even inside {...}. Looking up a dictionary key meant switching to the other quote character:
user = {"name": "Ada", "lang": "Python"}
print(f"{user["name"]} writes {user["lang"]}")
Python 3.10 sees f"{user[" as a complete string:
$ py -3.10 q1.py
File "q1.py", line 2
print(f"{user["name"]} writes {user["lang"]}")
^^^^
SyntaxError: f-string: unmatched '['
Python 3.12+ parses the expression the same way it would outside an f-string:
$ py -3.13 q1.py
Ada writes Python
The old workaround still works in every version, and many projects keep using it while they support Python older than 3.12:
user = {"name": "Ada", "lang": "Python"}
print(f"{user['name']} writes {user['lang']}")
Ada writes Python
Being able to reuse quotes matters most when the expression itself has strings in it, such as a method call with string arguments or a conditional expression. Here a format spec is chosen at runtime (the nested {...} inside a format spec is covered in Nested formatting):
value = 3.14159
wide = True
print(f"[{value:{"10" if wide else "6"}.2f}]")
$ py -3.13 n2.py
[ 3.14]
$ py -3.10 n2.py
File "n2.py", line 3
print(f"[{value:{"10" if wide else "6"}.2f}]")
^^
SyntaxError: f-string: expecting '}'
Backslashes in expressions
The old parser rejected any backslash in the expression part. That ruled out the common "\n".join(...):
words = ["alpha", "beta", "gamma"]
print(f"Words:\n{"\n".join(words)}")
$ py -3.13 b1.py
Words:
alpha
beta
gamma
Python 3.10 fails on both the quote and the backslash. Even with the quotes changed to '\n', it reports f-string expression part cannot include a backslash. The usual workaround was to put the string in a variable first, or to not use an f-string at all:
words = ["alpha", "beta", "gamma"]
nl = "\n"
print(f"Words:\n{nl.join(words)}")
print("Words:\n" + "\n".join(words))
Words:
alpha
beta
gamma
Words:
alpha
beta
gamma
In 3.12+ escape sequences of all kinds work in the expression part, including \\, \t and \N{...}:
path = r"C:\Users\ada\notes.txt"
print(f"{path.split('\\')[-1]}")
print(f"{'\N{EM DASH}'.join(['a', 'b'])} {'tab:\tend'!r}")
$ py -3.13 b3.py
notes.txt
a—b 'tab:\tend'
$ py -3.10 b3.py
File "b3.py", line 2
print(f"{path.split('\\')[-1]}")
^
SyntaxError: f-string expression part cannot include a backslash
For file paths, pathlib.PurePath(path).name is clearer than splitting on \\. The example is only there to show the backslash.
Multi-line expressions
In 3.12+ a replacement field can span several lines even in a single-quoted f-string, just as an expression in parentheses can. That helps with long expressions:
items = [("apple", 3, 0.5), ("pear", 2, 0.75), ("plum", 10, 0.2)]
print(f"Total: {
sum(
qty * price
for _, qty, price in items
):.2f}")
$ py -3.13 m1.py
Total: 5.00
$ py -3.10 m1.py
File "m1.py", line 2
print(f"Total: {
^
SyntaxError: unterminated string literal (detected at line 2)
Before 3.12 you had to switch to a triple-quoted f-string. This version works in both 3.10 and 3.13:
items = [("apple", 3, 0.5), ("pear", 2, 0.75), ("plum", 10, 0.2)]
print(f"""Total: {
sum(
qty * price
for _, qty, price in items
):.2f}""")
Total: 5.00
Only the {...} part may span lines. The literal text of a single-quoted f-string still can't contain a raw newline. If an expression gets this long, a local variable usually reads better than either form.
Comments inside expressions
Since the expression can span lines, 3.12 also allows # comments in it. A comment runs to the end of the line, so the closing } must go on a later line:
width, height = 1920, 1080
print(f"Area: {
width # pixels across
* height # pixels down
}")
$ py -3.13 c1.py
Area: 2073600
Python 3.10 rejected # even in a triple-quoted f-string:
$ py -3.10 c0.py
File "c0.py", line 5
}""")
^
SyntaxError: f-string expression part cannot include '#'
A # inside a string in the expression was always allowed: f"{'#' * 3}" gives ### on 3.10 and 3.13. It's only a comment when it's outside a string.
Arbitrary nesting
Before 3.12 each nested f-string needed a different quote type, so four levels was the maximum:
print(f"""{f'''{f"{f'{1 + 1}'}"}'''}""")
$ py -3.10 n0.py
2
With quote reuse, there's no limit set by quotes:
print(f"{f"{f"{f"{f"{f"{1 + 1}"}"}"}"}"}")
$ py -3.13 n1.py
2
$ py -3.10 n1.py
File "n1.py", line 1
print(f"{f"{f"{f"{f"{f"{1 + 1}"}"}"}"}"}")
^
SyntaxError: f-string: expecting '}'
Nobody should write code like that. The practical gain is in format specs: before 3.12 the expression parts inside a format spec could be nested only two levels deep (f-string: expressions nested too deeply). In 3.12+ the inner fields of a format spec can contain f-strings too:
value = 3.14159
print(f"[{value:{10}.{3}f}]")
print(f"[{value:{f"{10}"}.{3}f}]")
$ py -3.13 n3.py
[ 3.142]
[ 3.142]
On 3.10 the first line works and the second is a SyntaxError. In 3.12+ CPython stops at 150 nested f-strings (SyntaxError: too many nested f-strings), which you won't hit by accident.
The = specifier for debugging
Python 3.8 added the self-documenting expression {expr=} (bpo-36817). It prints the source text of the expression, an = sign and the value. It isn't new in 3.12, but it is the f-string feature most people still don't use:
name = "Ada"
count = 42
ratio = 2 / 3
print(f"{name=}")
print(f"{count=}")
print(f"{ratio=}")
print(f"{count = }")
print(f"{count * 2 = }")
print(f"{len(name)=}")
name='Ada'
count=42
ratio=0.6666666666666666
count = 42
count * 2 = 84
len(name)=3
Things to notice:
- The text before
=is copied exactly as written, whitespace included, so{count = }printscount = 42. - Any expression works, not just a name.
- By default the value is shown with
repr(), so strings get quotes.
It's handy as a quick replacement for print("x", x) when debugging:
def area(width, height):
print(f"debug: {width=}, {height=}, {width * height=}")
return width * height
area(3, 4)
point = {"x": 1, "y": 2}
print(f"{point["x"]=}, {point.get("z", 0)=}")
$ py -3.13 e3.py
debug: width=3, height=4, width * height=12
point["x"]=1, point.get("z", 0)=0
The last line uses quote reuse, so it needs 3.12+. With single quotes inside it also works on 3.8-3.11.
Combining = with !r, !s, !a and format specs
The = goes right after the expression, before any conversion or format spec. The rules for how the value is shown are:
{x=}:repr(x){x=!s}:str(x){x=!r}:repr(x)(the same as the default, but explicit){x=!a}:ascii(x){x=:spec}:format(x, spec), which for most types is thestr()form, notrepr()
import datetime
name = "Ada"
ratio = 2 / 3
day = datetime.date(2026, 10, 18)
print(f"{name=}")
print(f"{name=!s}")
print(f"{name=!r}")
print(f"{ratio=:.3f}")
print(f"{day=}")
print(f"{day=!s}")
print(f"{day=:%B %d, %Y}")
print(f"{ratio = :>10.2%}")
name='Ada'
name=Ada
name='Ada'
ratio=0.667
day=datetime.date(2026, 10, 18)
day=2026-10-18
day=October 18, 2026
ratio = 66.67%
Note how adding a format spec switches from repr() to format(). If you want the repr() padded or aligned, add !r before the spec:
city = "Zoë's Café"
print(f"{city=}")
print(f"{city=!a}")
print(f"{city=:>14}|")
print(f"{city=!r:>16}|")
city="Zoë's Café"
city="Zo\xeb's Caf\xe9"
city= Zoë's Café|
city= "Zoë's Café"|
For anything beyond quick debugging, use the logging module. Its messages can be turned off, and the arguments are formatted only when a message is actually emitted.
What still needs parentheses
The expression inside {...} is still followed by an optional !conversion and :format_spec, so some expressions are ambiguous without parentheses. This was true before 3.12 and still is:
import sys
x = 10
print(f"{(lambda n: n * 2)(x)}")
print(f"{(y := x + 1)} and y is {y}")
print(f"{x:=^9}")
print(f"{x != 3}")
print(f"{'a' if x > 5 else 'b'}")
print(f"{sys.version_info[:2]}")
$ py -3.13 g1.py
20
11 and y is 11
===10====
True
a
(3, 13)
- A
lambdamust be in parentheses, because its:would start the format spec. - The walrus operator must be in parentheses. Without them,
{x:=^9}isxwith the format spec=^9(fill with=, center, width 9). !=is recognized as the operator, not as a conversion.- A
:inside brackets, like a slice, is fine.
Better error messages
Since f-strings now go through the normal parser, syntax errors in them point at the real problem. In 3.10, the old parser wrapped the expression in parentheses and parsed it separately, so the error showed that rewritten text instead of your line:
total = 10
print(f"Total: {total +* 2}")
$ py -3.10 s1.py
File "s1.py", line 2
(total +* 2)
^
SyntaxError: f-string: invalid syntax
$ py -3.13 s1.py
File "s1.py", line 2
print(f"Total: {total +* 2}")
^
SyntaxError: f-string: expecting '=', or '!', or ':', or '}'
A forgotten pair of parentheses around a lambda now gets a specific message:
x = 10
print(f"{lambda n: n * 2}")
$ py -3.10 s2.py
File "s2.py", line 2
(lambda n)
^
SyntaxError: f-string: invalid syntax
$ py -3.13 s2.py
File "s2.py", line 2
print(f"{lambda n: n * 2}")
^^^^^^^^^
SyntaxError: f-string: lambda expressions are not allowed without parentheses
Changes in the tokenize module
This one matters only for tools that use the tokenize module (linters, formatters, syntax highlighters). Before 3.12 an f-string was one STRING token. Now it's split into FSTRING_START, FSTRING_MIDDLE and FSTRING_END tokens, with ordinary tokens for the expression in between:
import io, tokenize
src = 'f"Hi {name!r:>10}"\n'
for tok in tokenize.generate_tokens(io.StringIO(src).readline):
print(f"{tokenize.tok_name[tok.type]:<15} {tok.string!r}")
$ py -3.13 t1.py
FSTRING_START 'f"'
FSTRING_MIDDLE 'Hi '
OP '{'
NAME 'name'
OP '!'
NAME 'r'
OP ':'
FSTRING_MIDDLE '>10'
OP '}'
FSTRING_END '"'
NEWLINE '\n'
ENDMARKER ''
$ py -3.10 t1.py
STRING 'f"Hi {name!r:>10}"'
NEWLINE '\n'
ENDMARKER ''
Code that scanned STRING tokens to find all string literals in a file needs to handle the new tokens on 3.12+. Editors and highlighters had to update too. Old highlighters may color f"{d["k"]}" incorrectly even though Python accepts it.
Compatibility
The new syntax is a parse error on Python 3.11 and older, and the error happens when the module is compiled. A sys.version_info check in the same file can't guard it. If your package supports older versions:
- keep using the other quote type inside
{...}, and pull backslashes out into variables - configure your linter or formatter with your minimum Python version (for Ruff,
target-versionorrequires-pythoninpyproject.toml), so it doesn't produce or suggest 3.12-only f-strings
None of this changes what an f-string evaluates to. Code that worked on 3.11 gives the same result on 3.12+. Only the syntax errors and the tokenizer output differ.
Python 3.14 adds template strings (t-strings) with the t prefix. They use the same syntax as f-strings, including everything in this article, but they produce a Template object instead of a str, so a library can process the values before they are joined into text. They are described in their own article in this chapter.
Summary
| Feature | Since | Before that |
|---|---|---|
{expr=} self-documenting expression |
3.8 | write the name twice: f"x={x!r}" |
same quotes inside {...}: f"{d["k"]}" |
3.12 | use the other quote type: f"{d['k']}" |
backslashes in the expression: f"{'\n'.join(xs)}" |
3.12 | assign "\n" to a variable first |
# comments in the expression |
3.12 | not possible |
multi-line {...} in single-quoted f-strings |
3.12 | use a triple-quoted f-string |
| unlimited nesting of f-strings | 3.12 | at most 4 levels (one per quote type) |
| f-string syntax errors point at the real location | 3.12 | errors shown on rewritten (expr) text |
FSTRING_START/MIDDLE/END tokens |
3.12 | one STRING token |
Things to remember:
- In 3.12+ the expression inside
{...}follows the same rules as any expression in parentheses. lambdaand:=still need their own parentheses, because:starts the format spec.{x=}usesrepr(), but{x=:spec}usesformat(). Add!rto get a paddedrepr().- Code using the new syntax fails to compile on 3.11 and older. Stick to the old style in libraries that still support those versions.