Python f-Strings
What you will learn
- How to write an f-string and put values and expressions in
{ } - A first look at number formatting:
:.2fand alignment - The
=shortcut for debugging - How to print literal braces, and how quotes work inside an f-string
- The
!rconversion, and multi-line f-strings
1. What is an f-string?
An f-string (formatted string literal) is a string with the letter f in front of the opening quote. Anything inside curly braces { } is worked out and put into the text:
name = "Rina"
age = 25
print(f"Hello, {name}! You are {age}.")
Hello, Rina! You are 25.
f-strings need Python 3.6 or later, which is every current version. They are the clearest way to mix text and values, and they replace most uses of + with str():
print("Hello, " + name + "! You are " + str(age) + ".")
print(f"Hello, {name}! You are {age}.")
The second line does the same job, with no str() and no +.
Quick check: what does `f"{2 + 3} apples"` give?
5 apples. The braces hold an expression, and Python works it out.
2. Expressions inside braces
The braces can hold any expression: arithmetic, method calls, function calls, comparisons, or a condition:
x = 7
print(f"{age + 1}", f"{name.upper()}", f"{len(name)}", f"{x > 5}")
print(f"{'a' if x > 5 else 'b'}")
26 RINA 4 True
a
You can also read items out of lists and dictionaries:
d = {"k": "v", "n": 5}
items = ["a", "b"]
print(f"{d['k']}", f"{items[0]}{items[-1]}", f"{', '.join(items)}")
v ab a, b
Keep the expressions short. If a calculation is long, compute it on its own line first and put just the name in the braces.
3. A first look at formatting numbers
After the value you can add a colon and a format code. Two very common ones:
price = 1234.5678
print(f"{price:.2f}")
print(f"{price:,.2f}")
print(f"{age:>5}|")
print(f"{x:03d}")
1234.57
1,234.57
25|
007
| Code | Meaning |
|---|---|
:.2f |
a decimal number with exactly 2 digits after the point |
:,.2f |
the same, with commas between thousands |
:>5 |
right-align in a width of 5 characters |
:03d |
a whole number padded with zeros to width 3 |
Lesson 4.6 covers the whole format mini-language: alignment, signs, percentages, binary, dates and more.
4. The = shortcut for debugging
Adding = after an expression shows the expression and its value. It needs Python 3.8 or later and is handy when you check your code:
print(f"{x=}")
print(f"{name = }")
print(f"{age+1=}")
x=7
name = 'Rina'
age+1=26
Notice that the value of a text is shown with its quotes ('Rina'), which makes spaces visible.
5. Quotes and braces
Which quotes?
An f-string can use any quotes, but if the expression inside needs quotes, use a different kind from the outside ones:
print(f"{d['k']}")
print(f'{d["n"]}')
v
5
From Python 3.12 you may reuse the same kind of quote inside the braces, and put backslashes there. For code that must work in older versions, keep to different quotes and do not put backslashes inside the braces.
Printing curly braces
To show an actual { or }, double it:
print(f"{{braces}}")
print(f"{{{x}}}")
{braces}
{7}
In the second line, {{ and }} are the literal braces, and the middle {x} is the value.
6. Conversions: !r
After the expression you can force a conversion. The most useful is !r, which uses repr() and shows quotes and escapes:
print(f"{name!r}")
print(f"{name!s}")
print(f"{'é'!a}")
'Rina'
Rina
'\xe9'
!susesstr()(the normal text).!rusesrepr(): shows the value as code, which is excellent for finding hidden spaces.!ausesascii(): likerepr, but writes any non-ASCII character as an escape.
7. Multi-line f-strings
Use triple quotes for several lines, and put values in as usual. Neighbouring pieces are also joined:
text = f"""Name: {name}
Age: {age}"""
print(text)
print(f"multi {x}" f" line {age}")
Name: Rina
Age: 25
multi 7 line 25
Worked example: a receipt line
Print a receipt line with the item name, quantity, price and total.
item = "Notebook"
qty = 3
price = 49.5
total = qty * price
print(f"{item}: {qty} x {price:.2f} = {total:.2f}")
Notebook: 3 x 49.50 = 148.50
| Part | What it does |
|---|---|
{item} |
the text |
{qty} |
the whole number |
{price:.2f} |
the price with 2 decimals (49.50) |
{total:.2f} |
the total, calculated earlier and shown with 2 decimals |
The item and prices are made up for the example.
Common mistakes
- Forgetting the
f."Hello {name}"prints the braces and the wordnameas they are. - Using the same quote inside and outside in code that must run on older Python.
- Putting a long calculation in the braces. Work it out first, then use the name.
- Writing a single brace. Use
{{and}}for literal braces. - Passing text to a number code, such as
f"{name:d}"(ValueError: Unknown format code 'd' for object of type 'str').
Key takeaways
- Put
fbefore the quote, and values or expressions in{ }. - Add a colon and a code to format:
:.2f,:,.2f,:>5,:03d. {x=}shows the expression and its value (Python 3.8 and later).- Double the braces
{{ }}to print braces; use different quote types inside the braces. !rshows thereprof a value; triple quotes make multi-line f-strings.
Practice
1. With name = "Sam" and score = 90, write an f-string that prints Sam scored 90.
Show answer
print(f"{name} scored {score}").
2. What does f"{3 * 4} and {'hi'.upper()}" give?
Show answer
12 and HI.
3. Show 0.12345 with 3 digits after the decimal point.
Show answer
f"{0.12345:.3f}" gives 0.123.
4. What does f"{{x}}" print when x = 5?
Show answer
{x}. The doubled braces are literal, so the name is not replaced.
5. Use the debugging form to show both total and its value, when total = 9.
Show answer
print(f"{total=}") shows total=9.
6. Print the dictionary item person["city"] inside an f-string without using the same kind of quote twice.
Show answer
f"{person['city']}" (or f'{person["city"]}').