Sub topic 7
Formatting with f-strings
This chapter assumes you can run a Python script and use str, int, and float. You should also know how print() and str() versus repr() behave from earlier chapters. The examples use Python 3.12 unless a note says otherwise. Python 3.6 or later runs most of them.
The working model
An f-string is a string literal with an f before the opening quote. Inside it, each pair of braces is a replacement field holding a Python expression. When execution reaches the line, Python evaluates each expression and converts the result to text. It then joins the pieces into an ordinary str.
An f-string is not a template object. It is an expression that produces a plain string at the moment it runs, and nothing about the fields is stored in the result.
A field has up to three parts after the expression: {expression!conversion:format_spec}. This chapter covers the expression and the conversion. The next chapter covers the format spec in detail.
Basic replacement fields
name = "Ada"
langs = ["Python", "C"]
print(f"Hello, {name}!")
print(f"{name.upper()} knows {len(langs)} languages")This prints Hello, Ada! and then ADA knows 2 languages. Python converts values that are not strings with format(). For int, float, and str this gives the same text as str().
Any expression works
The braces accept an expression, not only a variable name. Arithmetic, method calls, indexing, function calls, and conditional expressions are all allowed. Statements such as assignments with = and if blocks are not.
price = 19.99
qty = 3
user = {"name": "Ada", "role": "admin"}
print(f"Total: {price * qty:.2f}")
print(f"Quantity is {'even' if qty % 2 == 0 else 'odd'}")
print(f"{user['name']} is {user['role']}")
print(f"{qty != 3}")The output is Total: 59.97, Quantity is odd, Ada is admin, and False.
Keep expressions short. If a field needs more than a method call or a small calculation, compute the value on its own line first and put the variable name in the braces. The string then stays easy to read.
Some expressions are ambiguous because : begins the format spec and ! begins a conversion. Wrap those expressions in parentheses:
print(f"{(y := 5)}")
print(f"{(lambda x: x * 2)(4)}")This prints 5 and then 8. The != operator in the previous example is the one exception. Python recognizes it, so it needs no parentheses.
Conversions: !s, !r, and !a
A conversion changes the value before formatting:
!scallsstr().!rcallsrepr().!acallsascii(), which is likerepr()but escapes non-ASCII characters.
text = "tab\there"
word = "café"
print(f"{text}")
print(f"{text!r}")
print(f"{word!a}")The first line prints the tab as whitespace. The second prints 'tab\there' with the quotes and the visible escape. The third prints 'caf\xe9'. Use !r in error messages and logs, where a stray space or newline in the value is often the bug you are looking for. Plain {value} is the same as {value!s} for most types, so you rarely need !s.
Literal braces
Because { starts a field, a literal brace must be doubled:
x = 5
print(f"{{x}} = {x}")This prints {x} = 5. The doubled braces apply only to the literal text. Inside a field you write braces normally, for example in a dictionary literal.
Quotes, backslashes, and Python versions
Before Python 3.12, the expression inside a field could not reuse the quote character that delimits the f-string, and it could not contain a backslash. Python 3.12 removed both limits.
user = {"name": "Ada"}
print(f"Name: {user['name']}")
print(f"Name: {user["name"]}")The first line works on every version that has f-strings. The second line is a SyntaxError before 3.12. If your code must run on older interpreters, alternate quote styles, or assign the value to a variable before the f-string. The same workaround applies to backslashes in expressions, such as "\n".join(rows) inside braces. Compute joined = "\n".join(rows) first and use {joined}.
A backslash in the literal part of the string, outside the braces, was always allowed. So f"{name}\n" works on all versions.
Multi-line f-strings
Triple-quoted f-strings keep their line breaks and any indentation inside them:
name = "Ada"
langs = ["Python", "C"]
report = f"""Name: {name}
Languages: {", ".join(langs)}"""
print(report)For longer text, adjacent string literals inside parentheses give you control over indentation. Each piece that contains a field needs its own f prefix:
msg = (
f"Name: {name}\n"
f"Languages: {', '.join(langs)}\n"
"Done."
)
print(msg)The last line has no f because it has no fields. Adding the prefix to it would be harmless, but leaving it off signals that nothing is substituted there.
Evaluated once, at the line it runs
An f-string captures values when the line executes. Changing a variable afterward does not change a string you already built:
n = 1
s = f"n is {n}"
n = 2
print(s)
show = lambda: f"n is {n}"
print(show())The first print shows n is 1. The second shows n is 2, because the f-string inside the lambda runs again on each call. If you need text that is rebuilt on demand, wrap the f-string in a function.
This also explains why you cannot store an f-string in a variable and fill it in later. The names must exist when the literal is evaluated. For a template that you fill in later, use str.format() or string.Template, which later chapters cover.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Output shows `{name}` literally | The `f` prefix is missing | Add `f` before the opening quote |
| `NameError: name 'x' is not defined` | The expression refers to a name that does not exist yet | Define the variable before the line runs, and check the spelling |
| `SyntaxError` about a single `}` or an unclosed `{` | A literal brace was not doubled | Write `{{` and `}}` for literal braces |
| `SyntaxError` with reused quotes or a backslash in a field (before 3.12) | Older parsers forbid both inside the expression | Use a different quote style, or compute the value first |
| Only the first line of a multi-line message is substituted | The `f` prefix is missing on later pieces | Put `f` on each literal that contains a field |
| `ValueError: Invalid format specifier` | The text after the colon is not a valid spec for that type | Check the spec against the value's type |
One more mistake is a design error rather than a syntax error. Never try to use an f-string on text supplied by a user, because the f prefix only works on literals in your source code. Building one from user input with eval() would let that user run arbitrary code. For templates that come from outside the program, use string.Template.
Choosing f-strings
Prefer f-strings for formatting text that you write in your own source code. They put each value where it appears in the output, they are checked for syntax when the file loads, and they are usually the fastest of the formatting options. Other approaches suit other cases. Use str.format() when the template text is stored separately from the values. Use string.Template when users write the template. Use % only to read or maintain existing code.
Exercises
Exercise
What does this code print, and why? n = 10 s = f"n={n}, {{n}}" n = 20 print(s)
Show answer
It prints n=10, {n}. The f-string is evaluated when the assignment line runs, so n is 10 at that point. Changing n to 20 afterward does not affect the string, which is already built. The doubled braces produce a literal {n}.
Exercise
This line fails on Python 3.11 but works on 3.12. Why, and how would you change it so it runs on both? data = {"city": "Oslo"} print(f"City: {data["city"]}")
Show answer
Before 3.12, the expression inside the braces cannot reuse the quote character that delimits the f-string, so the double quotes around "city" end the string early and cause a SyntaxError. Change the key to single quotes, as in f"City: {data['city']}", or assign city = data["city"] first and use {city}.