Formatting with f-strings
You've seen f-strings in passing — now let's master them. An f-string is the cleanest way to drop variables and expressions directly into text, so you can build readable output without clumsy concatenation.
The problem f-strings solve
Without f-strings, combining text and variables is awkward:
Python
You have to add + everywhere and convert numbers with str(). Easy to get wrong.
The f-string way
Put an f before the opening quote, then wrap any variable in { }:
Python
No +, no str() — Python inserts each value for you, converting numbers automatically.
You can put expressions inside the braces
Anything that produces a value works inside { }:
Python
Formatting numbers
Add a colon and a format spec to control how numbers look. Two common ones:
Python
Key takeaways
- An f-string starts with
fand uses{ }to insert values. - It auto-converts numbers, so no
str()and no+gluing. - You can put expressions inside the braces, like
{price * quantity}or{name.upper()}. - Use
{value:.2f}for decimals and{value:,}for thousands separators.
No comments yet. Add the first comment to start the discussion.