Text processing · 3 / 14 Theory

Formatting text and numbers

f-strings accept a format specifier after a colon, which controls the width, the alignment and the decimals. With it you can display well-aligned tables and listings.

The structure is {value:specifier}.

Decimals and thousands separator

price = 1234.5

print(f"{price:.2f}")    # 1234.50
print(f"{price:,.2f}")   # 1,234.50
print(f"{price:.0f}")    # 1234  (rounds)
print(f"{0.256:.1%}")    # 25.6%
print(f"{42:05d}")       # 00042  (pads with zeros up to 5 digits)

Width and alignment

A number after the colon sets the minimum width. The symbols <, > and ^ align to the left, to the right and to the center:

print(f"[{'sun':<8}]")    # [sun     ]
print(f"[{'sun':>8}]")    # [     sun]
print(f"[{'sun':^8}]")    # [  sun   ]
print(f"[{'sun':*^9}]")   # [***sun***]  (with a fill character)

By default, texts are aligned to the left and numbers to the right.

An aligned table

products = [("bread", 1.2), ("milk", 0.95), ("eggs", 2.35)]

print(f"{'Product':<10}{'Price':>8}")
for name, price in products:
    print(f"{name:<10}{price:>8.2f}")
print("-" * 18)
# Product      Price
# bread         1.20
# milk          0.95
# eggs          2.35
# ------------------

Text is multiplied with *: "-" * 18 is a line of 18 hyphens. It is the usual way to draw separators.

Alignment methods

There are also equivalent methods on the texts themselves:

print("sun".ljust(8) + "|")    # sun     |
print("sun".rjust(8) + "|")    #      sun|
print("sun".center(9, "*"))   # ***sun***
print("42".zfill(5))          # 00042

Width calculated in the program

If the width depends on a variable, it is nested between braces:

width = 10
print(f"[{'hello':>{width}}]")   # [     hello]

format and %

You will find two other ways of formatting in old code. They do the same as f-strings:

print("{} is {} years old".format("Ana", 30))   # Ana is 30 years old
print("{:.2f}".format(3.14159))                 # 3.14
print("%s is %d years old" % ("Ana", 30))         # Ana is 30 years old

In new code use f-strings: they are shorter and clearer.

Showing without formatting: repr

repr shows a value as you would write it in code, with quotes and visible special characters. It is very useful for debugging:

print(repr("hello\n"))   # 'hello\n'
print(repr("  "))        # '  '

Practice in Shopping receipt.