f-strings

Strings with inserted expression values: f"You have {points} pts".

On this page

Example

#
Python
name = "Emma"
points = 1240
accuracy = 0.8772

print(f"{name} has {points:,} points")
print(f"Accuracy: {accuracy:.1%}")
print(f"After bonus: {points * 1.1:.0f}")
Resultsaved result, you can check it
Emma has 1,240 points
Accuracy: 87.7%
After bonus: 1364

Definition and usage

#

An f-string is a string prefixed with the letter f, where curly braces let you insert any expression: a variable, a calculation, a function call. Python replaces it with text right where it sits.

After a colon inside the braces, you give the format: the number of decimal places ({avg:.2f}), a thousands separator ({n:,}), a percentage ({ratio:.0%}), or alignment ({name:<10}).

The notation {variable=} prints both the name and the value at once, which makes it much easier to quickly check values while debugging.

Syntax

#
Syntax
f"text {expression} text {number:.2f}"

More examples

#
Alignment and debugging
Python
rows = [("HTML", 11), ("Python", 12)]
for course, modules in rows:
    print(f"{course:<8}|{modules:>3}")

level = 7
print(f"{level=}")
Resultsaved result, you can check it
HTML | 11
Python | 12
level=7

Good practices

#
  • f-strings are more readable and faster than joining strings with + and str().
  • For a thousands separator other than a comma, such as a space, use {n:,} and then replace the comma: .replace(",", " ").

Related entries

#

Spotted a mistake or missing an example? Write to us.