Building sentences from values
Almost every program ends by turning its variables back into text a human reads: "Your total is $27.50", "3 new messages", "Level 7 complete". Doing that with concatenation is clumsy, because + only joins strings as lesson 2-3 showed, so every number needs a str(...) conversion and the line fills up with quotes and plus signs. Python added f-strings to fix exactly this.
Put an f immediately before the opening quote, and inside the string, anything wrapped in curly braces { } is evaluated as Python and its value is inserted into the text at that spot:
name = "Ada" age = 36 print(f"{name} is {age} years old.")
That outputs Ada is 36 years old.
The braces can hold any expression, not just a variable name, so {age + 10} computes first and then the result lands in the string. No str(...) is needed anywhere, because f-strings convert numbers to text for you.
The f stands for formatted. Without it, the braces are just ordinary characters and would print literally, which is the first thing to check when an f-string does not seem to work.
Two f-strings, one with a calculation
The second line does arithmetic inside the braces.
name = "Ada" age = 36 print(f"{name} is {age} years old.") print(f"In ten years she will be {age + 10}.")
Output
Ada is 36 years old. In ten years she will be 46.
age + 10 is computed to 46 before anything is inserted, so the string receives a finished value rather than an expression.
Changing either variable updates both sentences, which is the practical reason f-strings are worth using. The text and the values are written once each, in the place they belong, and the sentence reads almost like the output it produces.
Evaluating inside braces
print(f"{2 + 3} apples") outputs 5 apples.
Inside an f-string, braces evaluate their contents as Python first, so 2 + 3 becomes 5 and the printed text is 5 apples.
Without the leading f, the braces would be ordinary characters and the output would be the literal {2 + 3} apples.
That difference is the single most common f-string mistake, and it fails quietly. There is no error, just braces appearing in your output, which is why the missing f is the first thing to look for when the text prints wrong.
One f-string with two values
Both variables drop into one sentence.
city = "Lisbon" temp = 21 print(f"It is {temp} degrees in {city} today.")
Output
It is 21 degrees in Lisbon today.
Reading the pieces
- The string starts with
f", and{temp}and{city}sit exactly where their values belong in the sentence. - Everything outside the braces is copied literally, including the spaces around the values, which is why no extra spacing is needed.
- Compare it with the concatenation version,
"It is " + str(temp) + " degrees in " + city + " today.". Same output, and the f-string is the one you can read as a sentence.