CodeMIRAI
0 XP

Printing with f-strings

2 min read 6 runnable examples Quiz included

An f-string (formatted string) lets you put variables and expressions straight into text. Put an f before the opening quote and write expressions inside curly braces {}.

Python
name = "Mei"
age = 24
print(f"{name} is {age} years old.")

Compare that with joining strings by hand, which needs str() and careful spacing:

Python
name = "Mei"
age = 24
print(name + " is " + str(age) + " years old.")

Any expression works

Python
price = 250
quantity = 3
print(f"Total: {price * quantity}")
print(f"Name in capitals: {'mei'.upper()}")
print(f"Is it expensive? {price > 200}")

Formatting numbers

After the expression, a colon : starts a format specification:

Python
pi = 3.14159265
total = 1234567.891
rate = 0.0725

print(f"{pi:.2f}")        # 2 decimal places
print(f"{total:,.2f}")    # thousands separators
print(f"{rate:.1%}")      # as a percentage
print(f"{42:05d}")        # pad with zeros to 5 digits

Lining things up

Give a width, and optionally an alignment: < left, > right, ^ centre.

Python
items = [("Coffee", 3.5), ("Sandwich", 6.25), ("Cake", 4)]
for item, cost in items:
    print(f"{item:<10}{cost:>8.2f}")

This is how you print neat tables and receipts.

Debugging with =

Add = after an expression and Python prints the expression as well as its value. It is a handy shortcut while debugging:

Python
x = 7
y = 3
print(f"{x=}, {y=}, {x * y=}")
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.