Python String Formatting

Python string formatting is how you build text that includes values from variables, such as "Total: $45.00". Python 3.6 introduced f-strings, which are now the most popular and readable way to format strings.

f-string Basics

Put the letter f before the opening quote, then write variables or any expression inside curly braces.

name = "Usman"
items = 4
price = 2.5

print(f"Hi {name}, you bought {items} items.")
print(f"Total cost: {items * price}")
print(f"Name in capitals: {name.upper()}")
Hi Usman, you bought 4 items.
Total cost: 10.0
Name in capitals: USMAN

Formatting Numbers

After the expression, add a colon and a format specifier. .2f means two decimal places, a comma adds thousands separators, and % shows a fraction as a percentage.

amount = 1234567.891
ratio = 0.4567

print(f"{amount:.2f}")
print(f"{amount:,.2f}")
print(f"{ratio:.1%}")
print(f"{42:05d}")
1234567.89
1,234,567.89
45.7%
00042

Aligning and Padding Text

Use < for left, > for right and ^ for centre alignment, followed by a width. This is perfect for printing neat tables in the console.

rows = [("Rice", 12.5), ("Green Tea", 6), ("Olive Oil", 18.75)]

for name, price in rows:
    print(f"{name:<12}{price:>8.2f}")

print(f"{'END':*^20}")
Rice           12.50
Green Tea       6.00
Olive Oil      18.75
********END*********

Debugging with the = Specifier

Adding = after an expression prints both the expression and its value. It is a quick way to inspect variables while debugging.

width = 8
height = 3
print(f"{width=}, {height=}, {width * height=}")
width=8, height=3, width * height=24

format() and % Formatting

You will see two older styles in existing code. str.format() uses the same specifiers as f-strings, and the % operator comes from the C language. Both still work, but f-strings are shorter and faster.

city = "Dubai"
temp = 38.4

print("{} is {:.0f} degrees".format(city, temp))
print("%s is %.0f degrees" % (city, temp))
print(f"{city} is {temp:.0f} degrees")
Dubai is 38 degrees
Dubai is 38 degrees
Dubai is 38 degrees

To print a literal curly brace inside an f-string, double it: f"{{x}}" prints {x}. The format() method is still useful when the template string is stored somewhere else, like in a settings file.

Frequently asked questions

How do I format a number to 2 decimal places in Python?

Use an f-string with the .2f specifier, for example f"{value:.2f}". This rounds and always shows exactly two decimal places.

How do I add commas to a number in Python?

Use the comma specifier: f"{1234567:,}" gives 1,234,567. Combine it with decimals as f"{value:,.2f}".

Should I use f-strings or format()?

Use f-strings for most code because they are shorter and easier to read. Use format() when the template is created separately from the values.