Sub topic 7
Formatting with f-strings
This chapter assumes you can run a Python script and know str, int and float. It also assumes you have seen str() and repr() from the previous chapter. Python 3.6 or later is required for f-strings.
What an f-string is
An f-string is a string literal with an f before the opening quote. Inside it, anything in curly braces is a replacement field. Python evaluates the expression in the braces and inserts the result as text.
name = "Ada"
age = 36
print(f"{name} is {age} years old.")
print(f"Next year: {age + 1}")
print(f"Shout: {name.upper()}")Output:
Ada is 36 years old.
Next year: 37
Shout: ADAYou can put any expression in the braces: arithmetic, method calls, indexing, or a function call. You do not need to call str() yourself.
How evaluation works
Python evaluates an f-string when execution reaches that line, using the variables visible at that moment. The result is an ordinary str. Nothing about the original template is kept.
Conversions: !s, !r and !a
A conversion flag after the expression chooses how the value becomes text. !s uses str(), !r uses repr(), and !a uses ascii(). The default is str() behavior.
text = "tab\there"
print(f"{text}")
print(f"{text!r}")The first line prints the tab as whitespace. The second prints 'tab\there', with quotes and a visible escape sequence. Use !r in log and error messages, where you need to see exactly what the value contains.
Quotes and braces
The quote style inside a replacement field must differ from the one around the string. This applies before Python 3.12. Version 3.12 and later relax the rule.
user = {"name": "Ada"}
print(f"Hello, {user['name']}")To print a literal brace, double it:
n = 5
print(f"{{literal}} and {n}")
print(f"{{{n}}}")This prints {literal} and 5, then {5}. In the second line, {{ and }} produce the outer braces, and the middle {n} is a real field.
Long messages
Triple-quoted f-strings work for multi-line text. Adjacent literals also join into one string. Each piece needs its own f prefix, or its braces are printed literally.
item = "Widget"
qty = 3
message = (
f"Item: {item}\n"
f"Quantity: {qty}\n"
"Total fields: {2}"
)
print(message)The last line has no f, so it prints Total fields: {2} unchanged.
Common errors
- Forgetting the
f."{name}"prints the braces and the wordname. Python does not warn you. - Using a name that does not exist yet. Python raises
NameErrorat the line where the f-string runs. - Putting a backslash in older Pythons. Before 3.12, a backslash inside the braces is a syntax error. Compute the value first and put the variable in the braces.
- Hiding side effects in the braces. Any expression runs, so
f"{items.pop()}"removes an item every time the line runs.
The next chapter covers what follows a colon inside the braces: width, alignment, precision and number formats.
Exercise
Given n = 5, what does print(f"{{{n}}}") output, and why?
Show answer
It prints {5}. The doubled braces {{ and }} produce a literal opening and closing brace, and the middle {n} is a replacement field that inserts 5.