f-strings
Dropping values into text, and formatting numbers.
4 minute read
Big idea
An f-string puts values straight into text: write f before the quote, and anything in { } is worked out and dropped in.
The idea
name = "Ada"
age = 36
print(f"{name} is {age} years old.")
print(f"Next year she'll be {age + 1}.")output
Ada is 36 years old.
Next year she'll be 37.Run and edit it in the app.
No +, no str(), no commas. Any expression works inside the braces — maths, method calls, even another variable's len.
Forget the f, though, and the braces print literally:
total = 42
print("Your total is {total}")output
Your total is 42Run and edit it in the app.
Watch it
Formatting numbers
After a colon inside the braces you can say how to show the value:
price = 3.14159
print(f"{price:.2f}")
print(f"{1234567:,}")
print(f"{0.256:.1%}")
print(f"{7:03}")What does it print? Show the answer
3.14
1,234,567
25.6%
007Run and edit it in the app.
:.2f— a float with 2 decimal places (rounded).:,— commas between thousands.:.1%— as a percentage with 1 decimal place.:03— at least 3 wide, padded with zeros.
Lining things up
A width with < (left), > (right), or ^ (centre) pads a value with spaces — perfect for tables:
item = "Apple"
cost = 0.5
print(f"{item:<8}{cost:>6.2f}")
item = "Bread"
cost = 2.25
print(f"{item:<8}{cost:>6.2f}")
item = "Cheese"
cost = 11
print(f"{item:<8}{cost:>6.2f}")output
Apple 0.50
Bread 2.25
Cheese 11.00Run and edit it in the app.
{item:<8} makes the name 8 characters wide, padded on the right; {cost:>6.2f} makes the price 6 wide, right-aligned, with 2 decimals. Repeating the same print three times is clumsy — loops, coming up next, fix that.
Debugging trick
Put = after an expression and Python prints its text too:
x = 5
print(f"{x=}, {x * 2=}") # x=5, x * 2=10
What does f"{2/3:.3f}" produce?
Think of it like
A form letter with blanks: "Dear {name}, your order of {count} items…". The f-string fills in every blank right before it's printed.
Key terms
- f-string — A string starting with
fwhose{ }parts are filled in with values. - Format specifier — The part after
:in the braces that controls how a value looks, like.2f.
Check yourself
What does f"{2 + 2} cats" give?
What does f"{3.14159:.2f}" give?
What happens if you forget the f?