CodeBlanks Logo Icon CodeBlanks

f-string

Learn to embed variables in text with f"...".

f-string

An f-string is the modern way to embed variables or expressions inside a string. Put an f before the string and write variables inside {}:

name = "Alex"
print(f"Hello {name}")  # Hello Alex

f-strings were added in Python 3.6 and are the most common method today. You can also write expressions in the braces: f"Total: {3 + 5}".

f-string formatting

You can also format inside an f-string. After : you specify the format:

price = 19.99
print(f"Price: {price:.2f}")  # Price: 19.99
print(f"Percent: {0.85:.0%}")   # Percent: 85%

:.2f gives two decimals, :.0% gives a percentage. This is very handy for tables and reports.

Practice Print an f-string

Assign name = "Alex" and age = 25. Print print(f"{name} is {age}").

Starter code

main.py
# Write the f-string

Sample solution

main.py
name = "Alex"
age = 25
print(f"{name} is {age}")

Expected output

Alex is 25

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does f"Result: {2 + 3}" print?

  • Result: 5 Correct answer
  • Result: 2 + 3
  • Result: {5}
  • It raises an error

Explanation: The f-string evaluates the expression in the braces: 5.

2 Complete the f-string

Question
name = "Alex"
print(f"Hello ____")
Answer
name = "Alex"
print(f"Hello {name}")

Explanation: {name} embeds the variable in the f-string.

3 Match the f-string concepts

Term Meaning
f" f-string prefix
{} Embedding a variable
:.2f Two decimals
f"{x}" String with variable

All lessons in Beginner