🔤 Working with Text, lesson 5 of 5
f-strings
Drop variables and expressions straight into text, and format numbers neatly.
10 min
1 exercise
2 quizzes
0/3 solved
Getting Python ready… examples can run in a moment.
Joining text with + and str() gets messy. An
f-string is cleaner: put f before the opening
quote and write any variable or expression inside
{curly braces}. Python fills in the values.
Example
Your first f-strings
Remove the f before a string and run it. What happens to the braces?
Quiz
What does this print?
x squared is x ** 2
7 squared is 49
{x} squared is {x ** 2}
7 squared is 14
After a colon inside the braces you can add a format spec:
{price:.2f}shows exactly 2 decimal places{big:,}adds thousands separators{ratio:.0%}shows a percentage{name:>8}right-aligns in 8 characters (<left,^center)
Example
Formatting numbers
Change .2f to .3f, or .0% to .1%.
Quiz
What does this print?
Total: 12.5
Total: 12.50
Total: 13
Total: 12.500
Exercise
Receipt line
Use an f-string to build line so it reads exactly:
2 x Coffee = 7.00
The cost is quantity * price; show it with 2
decimal places.