Python Arena
Step 4 of 5

F-strings

Joining with + and str works, but long lines get clumsy, and commas add spaces you don't always want. An f-string lets you write a line the way it should look and mark the places where values go. Write f right before the opening quote, and put a variable's name in curly brackets { } inside the string. Python puts the variable's value in its place:

item = "pencils"
count = 12
print(f"You ordered {count} {item}.")
Output
You ordered 12 pencils.

The f stands for "formatted". The values can be of any type, so no str is needed. Everything outside the brackets is printed exactly as it is written, so you decide where every space goes.

Several values, and calculations

An f-string can have as many brackets as you need, and a bracket can hold a calculation as well as a variable:

name = "Ada"
price = 3
count = 12
print(f"{name} buys {count} pencils at {price} each.")
print(f"That's {count * price} in all.")
Output
Ada buys 12 pencils at 3 each.
That's 36 in all.

Compared with commas

Here is the first example with commas instead. The automatic spaces put a space before the full stop:

item = "pencils"
count = 12
print("You ordered", count, item, ".")
Output
You ordered 12 pencils .

To get rid of that space, you'd have to mix the two ways: commas for the words and + for the full stop, print("You ordered", count, item + "."). It works, but you have to think about every gap. The f-string says the whole line in one piece, exactly as it's printed.

Commas are fine for a quick look at some values. When the output has to look exactly right, an f-string is usually the easiest choice.

The missing f

Without the f, the string is an ordinary string, and the brackets are printed as they are:

city = "Oslo"
print("Welcome to {city}!")
print(f"Welcome to {city}!")
Output
Welcome to {city}!
Welcome to Oslo!

There's no error message: Python can't know that you meant an f-string. If you see curly brackets in your output, check for the f.

An f-string makes a string like any other, so you can also store it in a variable: label = f"{count} {item}".

Your task

Challenge 1 of 3

Fill in the blank so the program greets the user. If the user types Ada, the run looks like this:

Name: Ada
Hello, Ada!

Challenge 2

The last line prints extra spaces around the parentheses. Rewrite it with an f-string, so that a run looks like this:

Name: Ada
Age: 36
Ada (36 years)

Challenge 3

A notebook costs 4 and the customer buys 3 of them. The program asks for the product's name; the price and the amount are already in variables. Add one print with an f-string, so that a run looks like this:

Product: notebook
3 x notebook = 12 euros

Calculate the total inside the f-string, from the variables.