StringsChapter 19 of 114
f-Strings
Put values straight into text, and format them while you are there.
The f prefix
Put f in front of the quotes and anything in curly braces is evaluated and dropped into the text:
name = "Ada"
age = 36
print(f"{name} is {age}")Output
Ada is 36
No str() calls, no +, and the sentence still reads like a sentence. This is the default way to build text in modern Python.
Any expression fits
The braces hold an expression, not just a name:
price = 19.99
count = 3
print(f"{count} items, {price * count:.2f} total")
print(f"{name.upper()}" if (name := "ada") else "")Output
3 items, 59.97 total ADA
Formatting after the colon
A colon inside the braces introduces a format spec. This is where f-strings earn their keep:
value = 3.14159
print(f"{value:.2f}")
print(f"{value:10.2f}|")
print(f"{value:<10.2f}|")Output
3.14
3.14|
3.14 |.2f means two decimal places. The number before the dot is a minimum width, and < > ^ align left, right and centre.
Common specs
| Spec | Does | Result for 1234.5678 |
|---|---|---|
.2f | two decimals | 1234.57 |
, | thousands separators | 1,234.5678 |
,.2f | both | 1,234.57 |
>12 | right align in 12 | 1234.5678 |
e | scientific | 1.234568e+03 |
n = 1234.5678
print(f"{n:.2f}")
print(f"{n:,.2f}")
print(f"{n:>12.2f}|")Output
1234.57
1,234.57
1234.57|Percentages and padded integers come up constantly:
share = 0.3421
print(f"{share:.1%}")
print(f"{7:03d}")Output
34.2% 007
The = suffix for debugging
Put = after the expression and you get the expression itself as well as its value. It is built for print-debugging:
total = 42
items = 7
print(f"{total=}")
print(f"{total / items=}")Output
total=42 total / items=6.0
Braces and quotes
To print a literal brace, double it:
print(f"{{not a placeholder}}")Output
{not a placeholder}Since Python 3.12 you may reuse the same quote character inside the braces, so this is now legal:
data = {"name": "Ada"}
print(f"{data["name"]}")Output
Ada
Multi-line f-strings
Triple quotes work the same way:
name = "Ada"
items = 3
print(f"""Order for {name}
Items: {items}""")Output
Order for Ada Items: 3
Test yourself
3 questionsWhat does f"{3.14159:.2f}" give?
Show the answer
"3.14" — The part after the colon is a format spec, and .2f means two decimal places.
What does f"{total=}" print when total is 42?
Show the answer
total=42 — The = suffix prints the expression and its value, which is built for print-debugging.
How do you print a literal curly brace inside an f-string?
Show the answer
Double it: {{ — A doubled brace produces one literal brace in the output.
String Formatting
format(), the older % style, and how to line text up in columns.