Chapters
Python114 chapters

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:

Python
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:

Python
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:

Python
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

SpecDoesResult for 1234.5678
.2ftwo decimals1234.57
,thousands separators1,234.5678
,.2fboth1,234.57
>12right align in 12 1234.5678
escientific1.234568e+03
Python
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:

Python
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:

Python
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:

Python
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:

Python
data = {"name": "Ada"}
print(f"{data["name"]}")

Output

Ada

Multi-line f-strings

Triple quotes work the same way:

Python
name = "Ada"
items = 3
print(f"""Order for {name}
Items: {items}""")

Output

Order for Ada
Items: 3

Test yourself

3 questions

What 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.

Next chapter

String Formatting

format(), the older % style, and how to line text up in columns.