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}.")
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.")
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, ".")
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}!")
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}".