Automate everyday tasks with Python · Lesson 12 of 14
Reports and text templates
Turn numbers into readable reports: format with f-strings, fill templates with str.format and string.Template, wrap text and draw tables.
Most automation ends with a report: a summary that a person reads, an e-mail text, a file for a colleague. Python's string formatting turns raw numbers into neat, aligned text without any extra library.
Format codes in f-strings
Inside f-strings, a colon after the value starts a format code: :.2f two decimals, :, thousands separators, :% a percentage, :>10 right-align in 10 characters, :<10 left-align, :^10 centre, :05d pad with zeros.
price = 1234567.891
share = 0.0825
n = 42
print(f"{price:.2f}")
print(f"{price:,.2f}")
print(f"{share:.1%}")
print(f"[{'left':<10}] [{'right':>10}] [{'mid':^10}]")
print(f"invoice-{n:05d}")1234567.89 1,234,567.89 8.2% [left ] [ right] [ mid ] invoice-00042
Templates you fill in later
str.format() lets you write the template first and fill it later, for example once for every customer. Named fields like {name} take their values from keyword arguments or, with **, from a dictionary. string.Template uses $name instead, which is easier for non-programmers to edit in a separate text file.
from string import Template
letter = "Dear {name}, your order {order} of {total:.2f} EUR has shipped."
customers = [
{"name": "Ms Kowalski", "order": "A-17", "total": 59.9},
{"name": "Mr Haddad", "order": "A-18", "total": 120},
]
for c in customers:
print(letter.format(**c))
t = Template("Hello $name, your appointment is on $day.")
print(t.substitute(name="Priya", day="Tuesday"))
print(t.safe_substitute(name="Tom"))Dear Ms Kowalski, your order A-17 of 59.90 EUR has shipped. Dear Mr Haddad, your order A-18 of 120.00 EUR has shipped. Hello Priya, your appointment is on Tuesday. Hello Tom, your appointment is on $day.
substitute() raises a KeyError when a value is missing; safe_substitute() leaves the $placeholder in the text, which makes mistakes easy to spot.Wrapping long text: textwrap
textwrap.fill() breaks a long paragraph into lines of a given width, textwrap.shorten() cuts text to fit and adds [...], and textwrap.dedent() removes the common indentation from a multi-line string, so you can indent a template inside your code.
import textwrap
note = ("This week the script moved 128 files, created 6 new folders and found "
"3 files with the same name, which were renamed instead of overwritten.")
print(textwrap.fill(note, width=40))
print(textwrap.shorten(note, width=45, placeholder=" [...]"))
body = textwrap.dedent("""\
Summary
files: 128
folders: 6
""")
print(body, end="")This week the script moved 128 files, created 6 new folders and found 3 files with the same name, which were renamed instead of overwritten. This week the script moved 128 files, [...] Summary files: 128 folders: 6
A simple table
A small function can draw a text table with columns as wide as their longest value. Numbers are right-aligned, text left-aligned, the way spreadsheets do it.
def table(headers, rows):
widths = [max(len(str(x)) for x in col) for col in zip(headers, *rows)]
def line(values):
cells = []
for v, w in zip(values, widths):
cells.append(f"{v:>{w}}" if isinstance(v, (int, float)) else f"{v:<{w}}")
return " | ".join(cells)
print(line(headers))
print("-+-".join("-" * w for w in widths))
for r in rows:
print(line(r))
table(["Folder", "Files", "Share"],
[["images", 58, "45%"], ["documents", 41, "32%"], ["music", 29, "23%"]])Folder | Files | Share ----------+-------+------ images | 58 | 45% documents | 41 | 32% music | 29 | 23%
Writing the report to a file is the same text, sent to write() instead of print(). Building the report as a list of lines and joining them at the end keeps it easy to change.
from pathlib import Path
spent = {"rent": 950, "food": 412.35, "transport": 86.9}
lines = ["Monthly costs", "============="]
for item, amount in spent.items():
lines.append(f"{item:<10}{amount:>10,.2f}")
lines.append(f"{'total':<10}{sum(spent.values()):>10,.2f}")
Path("costs.txt").write_text("\n".join(lines) + "\n", encoding="utf-8")
print(Path("costs.txt").read_text(encoding="utf-8"), end="")Monthly costs ============= rent 950.00 food 412.35 transport 86.90 total 1,449.25
✎ Exercise
Print a receipt for basket: each line shows the item left-aligned in 10 characters, the quantity right-aligned in 3, and the line total right-aligned in 8 with two decimals. End with a TOTAL line in the same layout (leave the quantity column empty).
Hint: Use f"{item:<10}{qty:>3}{line_total:>8.2f}". For the empty column, format an empty string: {'':>3}.
basket = [("bread", 2, 1.80), ("cheese", 1, 6.75), ("apples", 6, 0.45)]
# your code here
Expected output:
bread 2 3.60 cheese 1 6.75 apples 6 2.70 TOTAL 13.05
Show a solution
basket = [("bread", 2, 1.80), ("cheese", 1, 6.75), ("apples", 6, 0.45)]
total = 0
for item, qty, price in basket:
line_total = qty * price
total += line_total
print(f"{item:<10}{qty:>3}{line_total:>8.2f}")
print(f"{'TOTAL':<10}{'':>3}{total:>8.2f}")bread 2 3.60 cheese 1 6.75 apples 6 2.70 TOTAL 13.05
Check yourself
1. What does f"{0.256:.1%}" give?
% multiplies by 100 and adds the percent sign; .1 keeps one decimal.
2. What does Template("Hi $name").safe_substitute() return?
safe_substitute leaves missing placeholders as they are.
3. Which format right-aligns a value in 8 characters?
> points right: the value is pushed to the right edge.