← Intro to programming with Python

f-strings: filling in the blanks

Put variables straight into text.

Start this lesson

Joining with + gets messy fast: quotes, plus signs, str() everywhere. An f-string is cleaner. Put the letter f just before the opening quote, then write any variable inside curly braces { }. Python fills in each blank with the value, and numbers work without str(). You can even ask for a set number of decimal places, which is perfect for money.

name = "Omar"
items = 3
total = 7.5
print(f"{name} bought {items} items for ${total:.2f}")

This shows: Omar bought 3 items for $7.50. The :.2f inside the braces means "show this number with exactly 2 decimal places".

Common mistake: forgetting the f. Without it, print("{name}") shows the braces and the word name, exactly as typed.

Anything that makes a value can go inside the braces, not just a variable: f"Double is {items * 2}".