f-strings
In this tutorial, we'll use f-strings to place values inside text.
An f-string is a string with an f before the opening quote.
name = "Mia"
print(f"Hello, {name}")
Output:
Hello, Mia
The value inside {} is inserted into the string.
Using Multiple Values
name = "Mia"
score = 87
print(f"{name} scored {score}")
Output:
Mia scored 87
You do not need to convert score with str(). The f-string handles that.
Expressions Inside Braces
You can put simple expressions inside {}:
price = 5
quantity = 4
print(f"Total: {price * quantity}")
Output:
Total: 20
Keep expressions short. If the calculation is complicated, store it in a variable first.
Using Methods Inside f-strings
name = "ada"
print(f"Hello, {name.capitalize()}")
Output:
Hello, Ada
Common Mistake
Forgetting the f means Python prints the braces as text:
name = "Mia"
print("Hello, {name}")
Output:
Hello, {name}
Correct:
print(f"Hello, {name}")
Use Clear Variable Names
F-strings are easiest to read when the variable names are clear:
customer_name = "Mia"
order_total = 18.50
print(f"{customer_name} owes £{order_total}")
This reads almost like English. If you find an f-string hard to understand, the problem might be the variable names, not the f-string itself.
Practice
Create variables for product, price, and quantity. Use an f-string to print a receipt line.