f-strings
Joining with + gets messy. An f-string lets you drop variables straight into text. Put f before the quote and the variable inside { }:
name = "Grace" print(f"Hi {name}, 2 + 2 = {2 + 2}")
Anything inside {} can be any expression, and it doesn't need str().
A method is a tool called with a dot and parentheses. For example, "ada".title() returns "Ada". It works inside braces too: f"{name.title()}".
See it run
pet = "otter" age = 4 print("Pet: " + pet + ", age " + str(age)) print(f"Pet: {pet}, next year {age + 1}")
The same facts printed two ways. The first needs + and str(); the second is an f-string.
Practice f-strings
Exercise 1
Replace the concatenated print in the code editor below with one f-string using name and langs. Print exactly: Grace knows 3 languages.
Exercise 2
A café till prints receipt lines. Using item, qty and each (price per item) from the code editor below, print exactly:
2 x coffee = 6
Work out the total inside the braces with *. Don't type the 6 yourself.
Exercise 3
A history app stores names in lower case. Use first, last and year from the code editor below. Using one f-string, print exactly:
Ada Lovelace was born in 1815 and would turn 211 in 2026.
- Capitalise the names with
.title()inside the braces. - Work out 211 from
yearinside the braces too.
Free lesson: use the editor to practice it.
Practice
Loading Python…Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.