f-strings

Put variables and calculations inside text. Start the string with f and use curly brackets.

Syntax

f"text {variable} more text"
f"{value * 2}"
  • Anything valid in Python can go inside the brackets.

Example

name = "Pip"
hp = 20
print(f"{name} has {hp} HP")
print(f"double: {hp * 2}")

Output:

Pip has 20 HP
double: 40

Common mistakes

  • Forgetting the f before the quote prints the brackets as they are.
  • Use different quote styles inside and outside: f"{d['key']}".

Practise it