f-Strings: Easy Formatting

Putting variables into text

Joining text with + and str() gets messy. An f-string is much easier: put an f before the quotes and write variables inside curly brackets { }.

name = "Asha"
age = 21
print(f"My name is {name} and I am {age} years old.")

Output

My name is Asha and I am 21 years old.

You can put any expression inside the brackets:

price = 250
quantity = 3
print(f"Total: {price * quantity} rupees")
print(f"Shouting: {'hello'.upper()}")

Output

Total: 750 rupees
Shouting: HELLO

Formatting numbers

After a colon : you can say how the value should look:

pi = 3.14159265
print(f"{pi:.2f}")
print(f"{pi:.4f}")

big = 1234567
print(f"{big:,}")

score = 0.875
print(f"{score:.1%}")

Output

3.14
3.1416
1,234,567
87.5%
FormatMeaningExample result
:.2f2 decimal places3.14
:,commas in big numbers1,234,567
:.1%as a percentage87.5%

Lining things up

A number after the colon sets a width. < lines up on the left, > on the right:

print(f"{'Item':<10}{'Price':>8}")
print(f"{'Tea':<10}{20:>8}")
print(f"{'Sandwich':<10}{120:>8}")

Output

Item         Price
Tea             20
Sandwich       120

Tip: f-strings are the modern way to format text in Python. Use them whenever you mix text and values.

HOME LEARN COMMUNITY DASHBOARD