The f-string
Programs spend a surprising share of their time producing text for humans: receipts, log lines, error messages, reports. Every language needs a way to drop computed values into a sentence, and the f-string is Python's standard tool for it.
An f-string is a string with a lowercase f in front of the quotes. Inside it, anything wrapped in curly braces {} is evaluated and its result is dropped into the text:
name = "Ada" age = 36 print(f"{name} is {age}") # Ada is 36 print(f"Next year: {age + 1}") # full expressions work
This replaces gluing pieces together with +, which forces you to convert every number with str() first. f-strings convert for you.
Code exercise · python
Run this. The last line shows a format spec: after a colon inside the braces, `.2f` means show the number as a float with exactly 2 decimal places.
Quiz
What does `print(f"{7 / 2:.1f}")` output?
Code exercise · python
Your turn. Using ONE f-string, print exactly: `3 x notebook costs $13.50`. Compute the total from the variables (do not type 13.50 yourself) and format it to 2 decimals.
Code exercise · python
One more, a weather report line. Using one f-string, print exactly `Lisbon: 21.5 degrees`, formatting the temperature to 1 decimal place.