loop
Working with strings

Module 2 · Working with strings · Lesson 3 of 4

f-strings

Gluing text together with + gets ugly fast — and it breaks the moment a number is involved, because you can't add a string to an int. The modern fix is the f-string: put an f before the opening quote, then drop variables straight into the text inside {curly braces}.

f"Hi {name}, you are {age}"
name = Adaage = 36
f"Hi , you are "
Hi Ada, you are 36

Each {name} is replaced by that variable's value, right where it sits — numbers included, no str() needed. You can even put a whole expression inside the braces.

Run it yourselfruns in your browser · Python
main.py

f-strings can also format the value, with a specifier after a colon. The handiest is :.2f — show a number to two decimal places, perfect for money. There are specifiers for alignment, percentages and more.

Run it yourselfruns in your browser · Python
main.py
✎ Your turnauto-checked · Python

Write a function receipt(item, price) that returns a string like 'apple costs $0.50' — the price always shown to exactly two decimal places.

solution.py

From here on, reach for f-strings whenever you build text — they're clearer, safer and the standard in modern Python. A quick quiz to lock the section in.