Level 1
0 / 100 XP

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
name = "Alex" age = 28 print("Hello " + name + ", you are " + str(age)) # works, but messy

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
name = "Alex" age = 28 print(f"Hello {name}, you are {age}") # Hello Alex, you are 28

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
name = "Alex" price = 20 quantity = 3 print(f"Total: {price * quantity}") # Total: 60 print(f"Name in caps: {name.upper()}") # Name in caps: ALEX

Formatting numbers

Add a colon and a format spec to control how numbers look. Two common ones:

Python
pi = 3.14159 print(f"{pi:.2f}") # 3.14 (2 decimal places) total = 1234567 print(f"{total:,}") # 1,234,567 (thousands separators)

Key takeaways

  • An f-string starts with f and 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.