Skip to content
Justice Tech School

String Formatting

An f-string starts with f and puts expressions inside curly braces. After a colon you can control the format: :.2f gives two decimals, :, adds thousand separators, :>8 right-aligns in 8 spaces.

The older .format() method and % formatting still exist, but f-strings are the modern choice.

Example
name = "Ada"
score = 91.5678
print(f"{name} scored {score:.2f}")
print(f"{1234567:,}")
print(f"[{name:>6}]")
print(f"{3 * 4=}")
print("{} is {} years old".format("Tunde", 30))

Result

Ada scored 91.57
1,234,567
[   Ada]
3 * 4=12
Tunde is 30 years old

Exercise

Start an f-string.

name = "Ada"
print("Hello {name}")

Quiz Test

What does f"{3.14159:.2f}" show?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.