Skip to content

02. Strings and text — Exercises

These exercises practice every idea of the Strings and text lesson. They use real values from the course datasets: order lines from data/sales_raw.csv, names from data/messy_names.txt, suppliers from data/legacy_latin1.csv and log lines from data/logs/app.log.

How to work:

  1. Read the task and the expected output (or the acceptance criteria).
  2. Copy the starter code into a script (for example exercise.py) in your project folder, next to the data/ folder. Replace each to-do comment with your code.
  3. Run the script with python exercise.py. Compare your output with the expected output.
  4. Stuck? Open one hint at a time. Open the solution only after a real attempt.

Some exercises use a for loop or a list, as in the lesson’s loops and lists section. Module 03 teaches loops in full.

Warm-up

Order O000051 in data/sales_raw.csv is dated "2023-01-04". Use slicing and int() to get the year, the month and the day as numbers. Print the sentence below. The month and the day must print without leading zeros.

Expected output
Year 2023, month 1, day 4
Starter
order_date = "2023-01-04"
# TODO: slice out the year, month and day and convert them to int
# TODO: print the sentence
Hint 1

The year is the first 4 characters: order_date[:4]. Count the positions of the month and the day: the dashes are at indexes 4 and 7.

Hint 2

int("01") is 1. Converting removes the leading zero for you.

Solution
order_date = "2023-01-04"
year = int(order_date[:4])
month = int(order_date[5:7])
day = int(order_date[8:])
print(f"Year {year}, month {month}, day {day}")
assert (year, month, day) == (2023, 1, 4)
assert order_date[4] == order_date[7] == "-"
Output
Year 2023, month 1, day 4

How it works:

  1. order_date[:4] takes indexes 0 to 3: '2023'.
  2. order_date[5:7] takes indexes 5 and 6: '01'. The stop index 7 (the second dash) is excluded.
  3. order_date[8:] takes everything from index 8 to the end: '04'.
  4. int() turns each piece into a number and drops the leading zero.

Alternative: split("-") cuts the date at the dashes. Use it when the parts can have different lengths.

order_date = "2023-01-04"
parts = order_date.split("-")
print(f"Year {int(parts[0])}, month {int(parts[1])}, day {int(parts[2])}")
Output
Year 2023, month 1, day 4

M02-W02 · Predict the output: index and slice

Section titled “M02-W02 · Predict the output: index and slice”
Warm-up

Predict the output: write down what each line prints. Then run the code and compare.

Acceptance criteria:

  • You wrote a prediction for each of the 6 lines before you ran the code.
  • Your prediction matches the Output in the solution. For each line you got wrong, you can name the rule you missed.
Starter
product = "Wireless Earbuds"
print(product[0], product[-1])
print(product[:8])
print(product[9:])
print(product[-7:-4])
print(product[::3])
print(len(product[8:9]), repr(product[8]))
# TODO: write your prediction for each line before you run it
Hint 1

Number the characters: W is 0, the space is 8 and E is 9. The string has 16 characters, so -1 is index 15.

Hint 2

A slice stops before its stop index. [::3] takes indexes 0, 3, 6, 9, 12 and 15.

Solution
product = "Wireless Earbuds"
print(product[0], product[-1])
print(product[:8])
print(product[9:])
print(product[-7:-4])
print(product[::3])
print(len(product[8:9]), repr(product[8]))
assert len(product) == 16
assert product[:8] + product[8:] == product
Output
W s
Wireless
Earbuds
Ear
WesEbs
1 ' '

How it works:

  1. product[0] is the first character W; product[-1] is the last, s.
  2. [:8] takes indexes 0 to 7: Wireless. Index 8 is the space.
  3. [9:] starts after the space: Earbuds.
  4. [-7:-4] takes indexes 9, 10 and 11 (−7, −6 and −5), because −4 is excluded: Ear.
  5. [::3] takes every third character from index 0: W, e, s, E, b, s.
  6. [8:9] is a slice of length 1 (9 − 8), the space. repr() shows it in quotes so you can see it.

Alternative: to get the two words without counting indexes, split at the space. Assigning the two pieces to two names in one line is called unpacking (module 04):

product = "Wireless Earbuds"
first_word, second_word = product.split()
print(first_word, second_word, second_word[:3])
Output
Wireless Earbuds Ear
Warm-up

Three region labels from data/sales_raw.csv have stray spaces and odd case. Clean each one to the canonical form (North, South, East). Print the raw and clean values with repr(), so the spaces are visible.

Expected output
' north' -> 'North'
'SOUTH ' -> 'South'
' eAsT ' -> 'East'
Starter
raw_1 = " north"
raw_2 = "SOUTH "
raw_3 = " eAsT "
# TODO: clean each label and print "raw -> clean" with repr()
Hint 1

Two methods do the job: one removes the spaces at the ends, one fixes the case.

Hint 2

Chain them: raw_1.strip().title(). {raw_1!r} in an f-string shows the value with repr().

Solution
raw_1 = " north"
raw_2 = "SOUTH "
raw_3 = " eAsT "
clean_1 = raw_1.strip().title()
clean_2 = raw_2.strip().title()
clean_3 = raw_3.strip().title()
print(f"{raw_1!r} -> {clean_1!r}")
print(f"{raw_2!r} -> {clean_2!r}")
print(f"{raw_3!r} -> {clean_3!r}")
assert (clean_1, clean_2, clean_3) == ("North", "South", "East")
Output
' north' -> 'North'
'SOUTH ' -> 'South'
' eAsT ' -> 'East'

How it works:

  1. strip() removes whitespace at both ends and returns a new string.
  2. title() makes the first letter of each word upper case and the rest lower case. eAsT becomes East.
  3. !r in a replacement field formats the value with repr(), so quotes and spaces show.

Alternative: capitalize() gives the same result for one-word labels. For a label with two words, such as "south west", title() gives South West and capitalize() gives South west.

M02-W04 · Fix the bug: the label stays dirty

Section titled “M02-W04 · Fix the bug: the label stays dirty”
Warm-up

Fix the bug: this code should print the city of store S11 cleanly, but the output keeps the spaces and the lower case.

store_city = " san francisco "
store_city.strip()
store_city.title()
print(f"[{store_city}]")
Output
[ san francisco ]

Change the code so that it prints:

Expected output
[San Francisco]
Starter
store_city = " san francisco "
store_city.strip() # TODO: fix these two lines
store_city.title()
print(f"[{store_city}]")
Hint 1

Strings are immutable. What happens to the value that strip() returns?

Hint 2

Assign the result back to the name, or chain both methods in one assignment.

Solution
store_city = " san francisco "
store_city = store_city.strip().title()
print(f"[{store_city}]")
assert store_city == "San Francisco"
Output
[San Francisco]

How it works:

  1. A string method never changes the string. It returns a new one.
  2. The buggy code threw both results away, so store_city kept its original value.
  3. store_city.strip().title() runs strip() first and calls title() on its result. The assignment keeps the final value.

Alternative: two separate assignments, store_city = store_city.strip() and store_city = store_city.title(), work too. One chained line is shorter and still easy to read.

Warm-up

Print three products from data/products.csv as a price list. The name is left-aligned in 22 characters. The price is right-aligned in 10 characters, with a thousands separator and 2 decimals.

Expected output
Wireless Earbuds 79.99
55-inch 4K Smart TV 1,299.00
Running Socks 3-Pack 14.99
Starter
name_1, price_1 = "Wireless Earbuds", 79.99
name_2, price_2 = "55-inch 4K Smart TV", 1299.0
name_3, price_3 = "Running Socks 3-Pack", 14.99
# TODO: print one aligned line per product
Hint 1

Text needs < and a width. Numbers need >, a width, , and .2f.

Hint 2

Build the price spec from five parts in this order: align, width, grouping, precision, type.

Solution
name_1, price_1 = "Wireless Earbuds", 79.99
name_2, price_2 = "55-inch 4K Smart TV", 1299.0
name_3, price_3 = "Running Socks 3-Pack", 14.99
line_1 = f"{name_1:<22}{price_1:>10,.2f}"
line_2 = f"{name_2:<22}{price_2:>10,.2f}"
line_3 = f"{name_3:<22}{price_3:>10,.2f}"
print(line_1)
print(line_2)
print(line_3)
assert len(line_1) == len(line_2) == len(line_3) == 32
Output
Wireless Earbuds 79.99
55-inch 4K Smart TV 1,299.00
Running Socks 3-Pack 14.99

How it works:

  1. :<22 pads each name with spaces on the right to 22 characters.
  2. :>10,.2f pads each price on the left to 10 characters, adds the comma in 1,299.00 and always shows 2 decimals.
  3. Every line has the same length (22 + 10), so the decimal points line up. The assert checks this.

Alternative: name_1.ljust(22) + format(price_1, ">10,.2f") builds the same line with a string method and the built-in format().

Warm-up

Format three rates for a report. The churn rate of data/customers.csv is 0.1926. The East region’s revenue grew from 448,918.63 USD in 2023 to 544,765.09 USD in 2024. The most common non-zero discount is 0.05. Print the lines below. The growth must show its sign.

Expected output
Churn rate: 19.3%
East growth: +21.4%
Discount: 5%
Starter
churn_rate = 0.1926
east_2023 = 448918.63
east_2024 = 544765.09
discount = 0.05
# TODO: compute the growth as a fraction and print the three lines
Hint 1

Growth as a fraction is new / old - 1. Do not multiply by 100: the % type does that.

Hint 2

:.1% gives one decimal, :+.1% adds the sign, and :.0% gives a whole percentage.

Solution
churn_rate = 0.1926
east_2023 = 448918.63
east_2024 = 544765.09
discount = 0.05
growth = east_2024 / east_2023 - 1
print(f"Churn rate: {churn_rate:.1%}")
print(f"East growth: {growth:+.1%}")
print(f"Discount: {discount:.0%}")
assert 0.21 < growth < 0.22
assert f"{-growth:+.1%}" == "-21.4%"
Output
Churn rate: 19.3%
East growth: +21.4%
Discount: 5%

How it works:

  1. % multiplies the value by 100 and adds a percent sign. .1 keeps one decimal.
  2. + shows the sign of every number, so a rise reads +21.4% and a fall reads -21.4% (the second assert).
  3. .0% rounds to a whole percentage: 5%.

Alternative: round(growth * 100, 1) gives the number 21.4, but then you must add + and % yourself. The format spec does all three steps and keeps growth unchanged.

Warm-up

An old system exports store S01 from data/stores.csv with | as the delimiter. Split the record into fields, print a readable sentence, and join the fields again with commas, as in a CSV file.

Expected output
Chicago (S01), North region, 2,850 m², opened 2009
S01,Chicago,North,2850,2009-03-14
Starter
record = "S01|Chicago|North|2850|2009-03-14"
# TODO: split the record at "|"
# TODO: print the sentence (the size needs a thousands separator)
# TODO: join the fields with "," and print the CSV line
Hint 1

record.split("|") returns a list of 5 strings. Get each field by its index.

Hint 2

The size is text. Convert it with int() before you use :,. The year is the first 4 characters of the date field.

Solution
record = "S01|Chicago|North|2850|2009-03-14"
fields = record.split("|")
store_id = fields[0]
city = fields[1]
region = fields[2]
size_sqm = int(fields[3])
opened_year = fields[4][:4]
print(f"{city} ({store_id}), {region} region, {size_sqm:,} m², opened {opened_year}")
print(",".join(fields))
assert len(fields) == 5
assert ",".join(fields).split(",") == fields
Output
Chicago (S01), North region, 2,850 m², opened 2009
S01,Chicago,North,2850,2009-03-14

How it works:

  1. split("|") cuts at each | and returns ['S01', 'Chicago', 'North', '2850', '2009-03-14'].
  2. fields[4][:4] first takes the date string, then slices its first 4 characters.
  3. int(fields[3]) makes a number, so :, can add the separator.
  4. ",".join(fields) puts the fields back together with commas between them. The second assert checks that splitting the CSV line gives the same fields again.

Alternative: record.replace("|", ",") gives the same CSV line in one step. Use split() when you need the individual fields, and replace() when you only change the delimiter.

M02-W08 · Predict the output: characters and bytes

Section titled “M02-W08 · Predict the output: characters and bytes”
Warm-up

Predict the output: the supplier city Köln comes from data/legacy_latin1.csv. Decide what each line prints.

Acceptance criteria:

  • You wrote a prediction for each of the 5 lines before you ran the code.
  • Your prediction matches the Output in the solution, and you can explain why the three lengths differ.
Starter
city = "Köln"
print(len(city))
print(len(city.encode("utf-8")))
print(len(city.encode("latin-1")))
print(city.encode("utf-8"))
print(ord("ö"), chr(246) == "ö")
# TODO: write your prediction for each line before you run it
Hint 1

len() of a str counts characters. len() of bytes counts bytes.

Hint 2

UTF-8 needs 2 bytes for ö; latin-1 needs 1. Python shows a byte that is not ASCII as \x and two hexadecimal digits.

Solution
city = "Köln"
print(len(city))
print(len(city.encode("utf-8")))
print(len(city.encode("latin-1")))
print(city.encode("utf-8"))
print(ord("ö"), chr(246) == "ö")
assert city.encode("utf-8").decode("utf-8") == city
assert len(city.encode("utf-8")) - len(city) == 1
Output
4
5
4
b'K\xc3\xb6ln'
246 True

How it works:

  1. The string has 4 characters: K, ö, l, n.
  2. UTF-8 writes K, l and n as 1 byte each and ö as 2 bytes (c3 b6): 5 bytes.
  3. latin-1 writes every character as exactly 1 byte: 4 bytes.
  4. The bytes print as b'K\xc3\xb6ln': the ASCII letters stay readable, the two bytes of ö show as hex.
  5. The code point of ö is 246, and chr(246) turns it back into ö.

Alternative: list(city.encode("utf-8")) shows the bytes as numbers, [75, 195, 182, 108, 110]. This view makes it clear that bytes are just numbers from 0 to 255.

Core

Line 265 of data/sales_raw.csv is below. It has a region with spaces, a product name with a double space and a price with a dollar sign. Split it, clean the region and the product, convert the price, quantity and discount, recompute the revenue, and check it against the last field. Print the two lines below.

Expected output
O003612 2023-08-16 South | Cotton Bed Sheet Set | 1 x 69.99
Revenue 69.99 matches file: True
Starter
raw = "O003612,2023-08-16,C01708,S06, South ,store,P010,Cotton Bed Sheet Set,Home,$69.99,1,0.0,69.99"
# TODO: split into fields
# TODO: clean region (index 4) and product (index 7)
# TODO: convert unit price (9), quantity (10), discount (11) and revenue (12)
# TODO: recompute the revenue and print the two lines
Hint 1

The line has no quoted fields, so split(",") is safe here. The columns are order_id, order_date, customer_id, store_id, region, channel, product_id, product, category, unit_price, quantity, discount, revenue.

Hint 2

" ".join(s.split()) collapses inner spaces. removeprefix("$") drops the dollar sign.

Hint 3

Revenue is round(unit_price * quantity * (1 - discount), 2).

Solution
import math
raw = (
"O003612,2023-08-16,C01708,S06, South ,store,"
"P010,Cotton Bed Sheet Set,Home,$69.99,1,0.0,69.99"
)
fields = raw.split(",")
region = fields[4].strip().title()
product = " ".join(fields[7].split())
unit_price = float(fields[9].removeprefix("$"))
quantity = int(fields[10])
discount = float(fields[11])
revenue = round(unit_price * quantity * (1 - discount), 2)
print(f"{fields[0]} {fields[1]} {region} | {product} | {quantity} x {unit_price:.2f}")
matches = math.isclose(revenue, float(fields[12]), abs_tol=0.01)
print(f"Revenue {revenue:.2f} matches file: {matches}")
assert len(fields) == 13
assert region == "South" and product == "Cotton Bed Sheet Set"
Output
O003612 2023-08-16 South | Cotton Bed Sheet Set | 1 x 69.99
Revenue 69.99 matches file: True

How it works:

  1. split(",") gives 13 fields, one per column.
  2. strip().title() turns ' South ' into 'South'.
  3. split() cuts the product name into words and drops the extra space; " ".join() puts the words back with single spaces.
  4. removeprefix("$") leaves '69.99', which float() can read.
  5. The recomputed revenue matches the file value, so every column was read correctly. The check uses math.isclose() with a tolerance of 0.01 USD, as module 01 teaches for floats: on some rows the file’s rounding differs from round() by one cent.

Alternative: fields[9].lstrip("$") also removes the dollar sign. removeprefix() is stricter: it removes exactly one $ and nothing else, which makes your intent clear.

M02-C02 · Fix the bug: a price with a thousands separator

Section titled “M02-C02 · Fix the bug: a price with a thousands separator”
Core

Fix the bug: the price of the 14-inch Ultrabook Laptop (P004) arrives as "$1,149.00" in data/sales_raw.csv. This conversion crashes:

price_text = "$1,149.00"
unit_price = float(price_text.strip("$"))
Output
ValueError: could not convert string to float: '1,149.00'

Fix the conversion so that it handles the dollar sign and the separator. Print the price with and without formatting.

Expected output
1149.0 1,149.00
Starter
price_text = "$1,149.00"
unit_price = float(price_text.strip("$")) # TODO: fix this line
print(unit_price, f"{unit_price:,.2f}")
Hint 1

Read the error: the dollar sign is gone, but float() does not accept the comma.

Hint 2

replace(",", "") removes every comma.

Solution
price_text = "$1,149.00"
unit_price = float(price_text.removeprefix("$").replace(",", ""))
print(unit_price, f"{unit_price:,.2f}")
assert unit_price == 1149.0
assert float("$79.99".removeprefix("$").replace(",", "")) == 79.99
Output
1149.0 1,149.00

How it works:

  1. removeprefix("$") gives '1,149.00'.
  2. replace(",", "") gives '1149.00', which float() reads as 1149.0.
  3. The f-string adds the separator back for display only: 1,149.00.
  4. The second assert checks that the same expression works for a price without a separator.

Alternative: translate() deletes both characters in one call, wherever they are:

price_text = "$1,149.00"
remove = str.maketrans("", "", "$,")
print(float(price_text.translate(remove)))
Output
1149.0

M02-C03 · Aligned table of revenue by region

Section titled “M02-C03 · Aligned table of revenue by region”
Core

Print the 2024 revenue of each region in data/sales.csv as a text table with a header, separator lines, a share column and a total row. The figures are given as CSV text. Column widths: 8, 16 and 8.

Expected output
Region Revenue (USD) Share
--------------------------------
East 544,765.09 27.9%
South 482,265.00 24.7%
North 477,729.41 24.5%
West 446,174.74 22.9%
--------------------------------
Total 1,950,934.24 100.0%
Starter
regions_csv = """East,544765.09
South,482265.00
North,477729.41
West,446174.74"""
# TODO: compute the total with a loop
# TODO: print the header, a separator, one row per region, a separator and the total
Hint 1

Loop over regions_csv.splitlines() twice: once to add up the total, once to print the rows. Each line splits into a name and a revenue string.

Hint 2

Give the header the same widths and alignments as the rows. The text header above a number column needs > too. The revenue spec has align, width, grouping and precision; the share spec has align, width, precision and the % type.

Solution
regions_csv = """East,544765.09
South,482265.00
North,477729.41
West,446174.74"""
lines = regions_csv.splitlines()
total = 0.0
for line in lines:
total += float(line.split(",")[1])
header = f"{'Region':<8}{'Revenue (USD)':>16}{'Share':>8}"
print(header)
print("-" * len(header))
for line in lines:
parts = line.split(",")
revenue = float(parts[1])
print(f"{parts[0]:<8}{revenue:>16,.2f}{revenue / total:>8.1%}")
print("-" * len(header))
print(f"{'Total':<8}{total:>16,.2f}{1:>8.1%}")
assert round(total, 2) == 1950934.24
assert len(header) == 32
Output
Region Revenue (USD) Share
--------------------------------
East 544,765.09 27.9%
South 482,265.00 24.7%
North 477,729.41 24.5%
West 446,174.74 22.9%
--------------------------------
Total 1,950,934.24 100.0%

How it works:

  1. The first loop adds each revenue to total. The share column needs the total first.
  2. The header uses the same widths and alignments as the rows: the text header Revenue (USD) is right-aligned like the numbers below it.
  3. "-" * len(header) makes a separator exactly as wide as the table.
  4. The total row reuses the specs, so its numbers line up. The total, 1,950,934.24 USD, is the 2024 revenue of the whole dataset.

Alternative: store the widths in variables (w_name, w_rev, w_share = 8, 16, 8) and use nested specs such as f"{parts[0]:<{w_name}}". Then you change a width in one place.

M02-C04 · Predict the output: format specs

Section titled “M02-C04 · Predict the output: format specs”
Core

Predict the output: each line uses a different part of the format spec mini-language. The brackets show where each field starts and ends.

Acceptance criteria:

  • You wrote a prediction for each of the 8 lines before you ran the code, including the exact number of spaces.
  • Your prediction matches the Output in the solution. For each line you got wrong, you can name the part of the spec you misread.
Starter
print(f"[{7:03d}]")
print(f"[{'S01':>6}]")
print(f"[{'S01':*^7}]")
print(f"[{1299:,.2f}]")
print(f"[{0.05:.0%}]")
print(f"[{-0.004:.2f}] [{-0.004:z.2f}]")
print(f"[{2.675:.2f}] [{0.125:.2f}]")
print(f"[{'Noise-Cancelling Headphones':.10}] [{1234567:_}]")
# TODO: write your prediction for each line before you run it
Hint 1

0 before the width pads with zeros. A fill character goes before the alignment sign. % multiplies by 100.

Hint 2

2.675 is stored as a value slightly below 2.675. 0.125 is exact, and an exact tie rounds to the even digit. A precision on a string cuts it.

Solution
print(f"[{7:03d}]")
print(f"[{'S01':>6}]")
print(f"[{'S01':*^7}]")
print(f"[{1299:,.2f}]")
print(f"[{0.05:.0%}]")
print(f"[{-0.004:.2f}] [{-0.004:z.2f}]")
print(f"[{2.675:.2f}] [{0.125:.2f}]")
print(f"[{'Noise-Cancelling Headphones':.10}] [{1234567:_}]")
assert f"{7:03d}" == "007"
assert len(f"{'S01':*^7}") == 7
Output
[007]
[ S01]
[**S01**]
[1,299.00]
[5%]
[-0.00] [0.00]
[2.67] [0.12]
[Noise-Canc] [1_234_567]

How it works:

  1. 03d: width 3, padded with zeros.
  2. >6: right-aligned in 6 characters, so 3 spaces come first.
  3. *^7: centered in 7 characters with * as the fill: 2 stars on each side.
  4. ,.2f: thousands separator and 2 decimals, also for an int.
  5. .0%: 0.05 × 100 = 5, no decimals.
  6. -0.004 rounds to -0.00. The z option turns negative zero into 0.00.
  7. 2.675 is really 2.67499…, so it rounds down. 0.125 is an exact tie and rounds to the even digit 2.
  8. .10 on a string keeps the first 10 characters. _ groups digits with underscores.

Alternative: test one spec at a time with the built-in format() in the REPL, for example >>> format(0.125, ".2f").

M02-C05 · Normalize names before comparing

Section titled “M02-C05 · Normalize names before comparing”
Core

Lines 2 and 13 of data/messy_names.txt are the same customer. Read the file, clean both lines with strip, collapse and title case, and show that they are still not equal. Then normalize both to NFC and compare again. Print the lines below.

Expected output
Zoë O'Brien (11) vs Zoë O'Brien (12): False
After NFC: 11 vs 11: True
Starter
import unicodedata
from pathlib import Path
lines = Path("data/messy_names.txt").read_text(encoding="utf-8").splitlines()
# TODO: clean lines[1] and lines[12] (strip, collapse spaces, title case)
# TODO: print both, their lengths and the comparison
# TODO: normalize both to NFC and compare again
Hint 1

Line 2 is lines[1] and line 13 is lines[12], because indexes start at 0.

Hint 2

unicodedata.normalize("NFC", s) composes accents. Compare the lengths before and after.

Solution
import unicodedata
from pathlib import Path
lines = Path("data/messy_names.txt").read_text(encoding="utf-8").splitlines()
name_a = " ".join(lines[1].split()).title()
name_b = " ".join(lines[12].split()).title()
print(f"{name_a} ({len(name_a)}) vs {name_b} ({len(name_b)}): {name_a == name_b}")
nfc_a = unicodedata.normalize("NFC", name_a)
nfc_b = unicodedata.normalize("NFC", name_b)
print(f"After NFC: {len(nfc_a)} vs {len(nfc_b)}: {nfc_a == nfc_b}")
assert name_a != name_b
assert nfc_a == nfc_b == "Zoë O'Brien"
Output
Zoë O'Brien (11) vs Zoë O'Brien (12): False
After NFC: 11 vs 11: True

How it works:

  1. Line 2 is "ZOË o'brien". Title case gives Zoë O'Brien with a composed ë (one code point).
  2. Line 13 is in NFD form: its ë is e followed by a combining diaeresis. It looks the same but has 12 code points.
  3. == compares code points, so the two strings differ.
  4. NFC turns e + combining mark into the single code point ë. Both strings now have 11 code points and compare equal.

Alternative: normalize first, before every other step. It does not change the result here, but it is the safer order: later steps such as title() and len() then always see composed characters.

M02-C06 · Fix the bug: read the legacy supplier file

Section titled “M02-C06 · Fix the bug: read the legacy supplier file”
Core

Fix the bug: this code should print the header and the first two suppliers of data/legacy_latin1.csv, but it crashes.

from pathlib import Path
text = Path("data/legacy_latin1.csv").read_text(encoding="utf-8")
Output
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 49: invalid continuation byte

Fix it so that it prints:

Expected output
supplier_id,supplier,city,country,since
SUP01,Café Müller GmbH,Köln,Germany,2015
SUP02,Textiles Señora,Málaga,Spain,2017
12 suppliers
Starter
from pathlib import Path
text = Path("data/legacy_latin1.csv").read_text(encoding="utf-8") # TODO: fix
lines = text.splitlines()
print(lines[0])
print(lines[1])
print(lines[2])
print(len(lines) - 1, "suppliers")
Hint 1

The byte 0xe9 is é in a common one-byte encoding of Western Europe.

Hint 2

The file is latin-1 (ISO-8859-1). Pass that name as the encoding.

Solution
from pathlib import Path
text = Path("data/legacy_latin1.csv").read_text(encoding="latin-1")
lines = text.splitlines()
print(lines[0])
print(lines[1])
print(lines[2])
print(len(lines) - 1, "suppliers")
assert "Café Müller" in lines[1]
assert len(lines) == 13
Output
supplier_id,supplier,city,country,since
SUP01,Café Müller GmbH,Köln,Germany,2015
SUP02,Textiles Señora,Málaga,Spain,2017
12 suppliers

How it works:

  1. The error says that byte 49 (0xe9) is not valid UTF-8 at that place. In latin-1, 0xe9 is é.
  2. encoding="latin-1" decodes each byte as one character, so Café Müller, Köln and Málaga appear correctly.
  3. The first assert checks a known name. latin-1 never raises an error, so this check is the only proof that the guess was right.

Alternative: read the bytes first and decode them yourself. This makes the two steps visible and lets you try several encodings on the same bytes:

from pathlib import Path
raw = Path("data/legacy_latin1.csv").read_bytes()
print(raw.decode("latin-1").splitlines()[1])
print(raw.decode("cp1252").splitlines()[1])
Output
SUP01,Café Müller GmbH,Köln,Germany,2015
SUP01,Café Müller GmbH,Köln,Germany,2015
Core

A system wrote supplier cities as UTF-8, and a second system read them as latin-1. The cities now look garbled. Repair each one and print the garbled and repaired values side by side, with the garbled value left-aligned in 14 characters.

Expected output
Köln -> Köln
Málaga -> Málaga
Zürich -> Zürich
São Paulo -> São Paulo
Starter
garbled = ["Köln", "Málaga", "Zürich", "São Paulo"]
# TODO: for each city, undo the wrong decoding and print both values
Hint 1

Reverse the mistake. First get the original bytes back, then decode them correctly.

Hint 2

city.encode("latin-1") gives the original UTF-8 bytes. Then .decode("utf-8").

Solution
garbled = ["Köln", "Málaga", "Zürich", "São Paulo"]
repaired = []
for city in garbled:
fixed = city.encode("latin-1").decode("utf-8")
repaired.append(fixed)
print(f"{city:<14} -> {fixed}")
assert repaired == ["Köln", "Málaga", "Zürich", "São Paulo"]
Output
Köln -> Köln
Málaga -> Málaga
Zürich -> Zürich
São Paulo -> São Paulo

How it works:

  1. In UTF-8, ö is the two bytes c3 b6. Read as latin-1, those bytes are the two characters à and .
  2. encode("latin-1") turns each garbled character back into its byte, so you get c3 b6 again.
  3. decode("utf-8") reads the two bytes as one character: ö.
  4. Mojibake strings are longer than the real ones (Köln has 5 characters, Köln 4), because each accented letter became two characters.

Alternative: the third-party package ftfy (“fixes text for you”) detects and repairs mojibake automatically, including text that was garbled twice. For a known, single mistake, the two-step repair above needs no extra package.

Core

Interpret a result: this code prints customer names from data/messy_names.txt with their line numbers in an aligned table. One row is out of line in the output: its number sits too far to the left.

from pathlib import Path
lines = Path("data/messy_names.txt").read_text(encoding="utf-8").splitlines()
print(f"{lines[3].strip():<24}{4:>4}")
print(f"{lines[7].strip():<24}{8:>4}")
print(f"{lines[15].strip():<24}{16:>4}")
Output
Björk Guðmundsdóttir 4
José García 8
NGUYỄN văn an 16

Explain why the José García row is misaligned. Then fix the code so that every row lines up:

Expected output
Björk Guðmundsdóttir 4
José García 8
NGUYỄN văn an 16
Starter
from pathlib import Path
lines = Path("data/messy_names.txt").read_text(encoding="utf-8").splitlines()
# TODO: fix the alignment of the three rows
print(f"{lines[3].strip():<24}{4:>4}")
print(f"{lines[7].strip():<24}{8:>4}")
print(f"{lines[15].strip():<24}{16:>4}")
Hint 1

The width in a format spec counts code points, not the characters you see. Compare len(lines[7]) with the number of letters you count on screen.

Hint 2

Line 8 is in NFD form. Normalize it to NFC before formatting.

Solution
import unicodedata
from pathlib import Path
lines = Path("data/messy_names.txt").read_text(encoding="utf-8").splitlines()
name_4 = unicodedata.normalize("NFC", lines[3].strip())
name_8 = unicodedata.normalize("NFC", lines[7].strip())
name_16 = unicodedata.normalize("NFC", lines[15].strip())
print(f"{name_4:<24}{4:>4}")
print(f"{name_8:<24}{8:>4}")
print(f"{name_16:<24}{16:>4}")
assert len(lines[7]) == 13 and len(name_8) == 11
Output
Björk Guðmundsdóttir 4
José García 8
NGUYỄN văn an 16

How it works:

  1. Interpretation: José García on line 8 is stored in NFD form: 11 visible letters, but 13 code points, because é and í are each a letter plus a combining accent.
  2. The spec :<24 pads to 24 code points. It adds 11 spaces to the NFD name instead of 13. On screen, the two combining accents take no space, so the row is 2 characters short and the number shifts left.
  3. NFC composes each accent into its letter. The name then has 11 code points, gets 13 spaces, and lines up.

Alternative: the same problem appears with characters that take two columns on screen, such as Chinese or Japanese characters and most emoji. Their code point count is less than their screen width. For those, the third-party package wcwidth measures the real display width.

M02-C09 · Choose and justify: fix the case of product names

Section titled “M02-C09 · Choose and justify: fix the case of product names”
Core

Choose a method and justify it: a store manager typed three product names by hand: "chef's knife set", "55-inch 4k smart tv" and "NON-SLIP yoga mat". You need the official spellings from data/products.csv. Compare two approaches: (a) title() and (b) a case-insensitive lookup in the catalog text. Print both results for each name, choose one, and explain why.

Expected output
chef's knife set title(): Chef'S Knife Set catalog: Chef's Knife Set
55-inch 4k smart tv title(): 55-Inch 4K Smart Tv catalog: 55-inch 4K Smart TV
NON-SLIP yoga mat title(): Non-Slip Yoga Mat catalog: Non-Slip Yoga Mat
Starter
from pathlib import Path
catalog = Path("data/products.csv").read_text(encoding="utf-8")
typed = ["chef's knife set", "55-inch 4k smart tv", "NON-SLIP yoga mat"]
# TODO: for each name, print the title() result
# TODO: and the official spelling found in the catalog text
Hint 1

catalog.casefold().find(name.casefold()) gives the position of the name in the catalog, whatever the case.

Hint 2

These names are plain ASCII, so case folding does not change their length. Slice the original catalog at that position: catalog[pos:pos + len(name)].

Solution
from pathlib import Path
catalog = Path("data/products.csv").read_text(encoding="utf-8")
folded_catalog = catalog.casefold()
typed = ["chef's knife set", "55-inch 4k smart tv", "NON-SLIP yoga mat"]
official = []
for name in typed:
pos = folded_catalog.find(name.casefold())
match = catalog[pos : pos + len(name)]
official.append(match)
print(f"{name:<20} title(): {name.title():<20} catalog: {match}")
assert official == ["Chef's Knife Set", "55-inch 4K Smart TV", "Non-Slip Yoga Mat"]
Output
chef's knife set title(): Chef'S Knife Set catalog: Chef's Knife Set
55-inch 4k smart tv title(): 55-Inch 4K Smart Tv catalog: 55-inch 4K Smart TV
NON-SLIP yoga mat title(): Non-Slip Yoga Mat catalog: Non-Slip Yoga Mat

How it works:

  1. title() starts a new word after every non-letter. It gives Chef'S (after the apostrophe), Inch and Tv (it lowercases the rest of each word). Only the yoga mat comes out right.
  2. The lookup case-folds both the catalog and the typed name, finds the position of the match, and slices the original catalog there. That gives the exact official spelling.
  3. Choice: the catalog lookup. Product names follow brand rules (TV, 4K, 55-inch) that no case method knows. The official list is the only reliable source of truth, and a lookup also shows you when a typed name is not in the catalog (find() returns -1).

Alternative: this text search matches substrings, so "tent" would also match inside other text. Module 04 builds a dictionary from case-folded name to official name, which matches whole names only and is faster for many lookups.

M02-C10 · Count messy product names in the raw sales file

Section titled “M02-C10 · Count messy product names in the raw sales file”
Core

Read data/sales_raw.csv with the csv module. For each line, clean the product name by collapsing whitespace. Count how many lines needed a change, and how many distinct spellings exist before and after cleaning. Print the lines below.

Expected output
Lines: 1,200
Lines with a messy product name: 95 (7.9%)
Distinct spellings: 90 -> 30
Starter
import csv
from pathlib import Path
lines = Path("data/sales_raw.csv").read_text(encoding="utf-8").splitlines()
rows = list(csv.reader(lines))[1:]
# TODO: build a list of raw names and a list of clean names (column 7)
# TODO: count the lines where the clean name differs from the raw name
# TODO: print the three lines
Hint 1

True counts as 1 in arithmetic (module 01). changed += raw != clean adds 1 for each changed name.

Hint 2

len(set(names)) gives the number of distinct values in a list.

Solution
import csv
from pathlib import Path
lines = Path("data/sales_raw.csv").read_text(encoding="utf-8").splitlines()
rows = list(csv.reader(lines))[1:]
raw_names = []
clean_names = []
changed = 0
for row in rows:
raw = row[7]
clean = " ".join(raw.split())
raw_names.append(raw)
clean_names.append(clean)
changed += raw != clean
print(f"Lines: {len(rows):,}")
print(f"Lines with a messy product name: {changed} ({changed / len(rows):.1%})")
print(f"Distinct spellings: {len(set(raw_names))} -> {len(set(clean_names))}")
assert changed == 95
assert len(set(clean_names)) == 30
Output
Lines: 1,200
Lines with a messy product name: 95 (7.9%)
Distinct spellings: 90 -> 30

How it works:

  1. csv.reader() splits each line correctly, even the lines with quoted dates and prices.
  2. " ".join(raw.split()) removes spaces at both ends and collapses double spaces inside.
  3. raw != clean is True for a messy name. Adding a bool to an int adds 1 or 0, so changed counts the messy lines.
  4. 95 of 1,200 lines (7.9%) had stray spaces. They made 90 spellings out of the 30 real products.

Alternative: the csv module can also read from an open file: with open("data/sales_raw.csv", encoding="utf-8", newline="") as f: followed by rows = list(csv.reader(f))[1:] in the indented block. The with statement closes the file for you. Module 07 explains it.

M02-C11 · Refactor: from concatenation to an f-string

Section titled “M02-C11 · Refactor: from concatenation to an f-string”
Core

Refactor: this code builds a report line for store S07 (New York) with + and str(). It works, but it is hard to read, and the numbers have no separators and a missing trailing zero. Rewrite it as one f-string with format specs.

store_id = "S07"
city = "New York"
revenue = 468290.16
share = 0.130205
line = (
"Store " + store_id + " (" + city + "): " + str(round(revenue, 1))
+ " USD, " + str(round(share * 100, 1)) + "% of total"
)
print(line)
Output
Store S07 (New York): 468290.2 USD, 13.0% of total

The refactored line must show the revenue with a separator and 2 decimals:

Expected output
Store S07 (New York): 468,290.16 USD, 13.0% of total
Starter
store_id = "S07"
city = "New York"
revenue = 468290.16
share = 0.130205
# TODO: build the same line with one f-string
Hint 1

Put each variable in its own replacement field: f"Store {store_id} ({city}): ...".

Hint 2

:,.2f for the revenue and :.1% for the share. The % type replaces both * 100 and the "%" text.

Solution
store_id = "S07"
city = "New York"
revenue = 468290.16
share = 0.130205
line = f"Store {store_id} ({city}): {revenue:,.2f} USD, {share:.1%} of total"
print(line)
assert "468,290.16" in line
assert line.endswith("13.0% of total")
Output
Store S07 (New York): 468,290.16 USD, 13.0% of total

How it works:

  1. The f-string shows the shape of the final line at a glance: text and fields in their real order.
  2. f-strings convert values for you, so every str() call disappears.
  3. :,.2f formats the revenue with a separator and exactly 2 decimals. round(revenue, 1) had dropped a digit, and round() never adds trailing zeros.
  4. :.1% multiplies by 100, rounds and adds % in one step.

Alternative: if the same layout is used for all 12 stores, store it once as a template and fill it with str.format():

template = "Store {} ({}): {:,.2f} USD, {:.1%} of total"
print(template.format("S01", "Chicago", 406532.46, 0.113035))
Output
Store S01 (Chicago): 406,532.46 USD, 11.3% of total

M02-C12 · Accent-free search keys for supplier cities

Section titled “M02-C12 · Accent-free search keys for supplier cities”
Core

Build an accent-free, lowercase search key for each supplier city in data/legacy_latin1.csv (column 2). Print each city and its key in two aligned columns. Then show that a search for zurich finds the right city.

Expected output
Köln koln
Málaga malaga
Besançon besancon
Malmö malmo
São Paulo sao paulo
Zürich zurich
Genève geneve
Montréal montreal
Reykjavík reykjavik
Bogotá bogota
Göteborg goteborg
Asunción asuncion
Search 'zurich' -> Zürich
Starter
import unicodedata
from pathlib import Path
lines = Path("data/legacy_latin1.csv").read_text(encoding="latin-1").splitlines()
# TODO: for each supplier line, take the city and build its key
# TODO: print "city key" in two columns (city left-aligned in 12 characters)
# TODO: find the city whose key is "zurich"
Hint 1

The file has no quoted fields, so line.split(",")[2] is the city. Skip the header with lines[1:].

Hint 2

Key recipe: unicodedata.normalize("NFKD", city).encode("ascii", "ignore").decode().casefold(). To find a key, collect the keys in a list and use the list method index().

Solution
import unicodedata
from pathlib import Path
lines = Path("data/legacy_latin1.csv").read_text(encoding="latin-1").splitlines()
cities = []
keys = []
for line in lines[1:]:
city = line.split(",")[2]
decomposed = unicodedata.normalize("NFKD", city)
key = decomposed.encode("ascii", "ignore").decode().casefold()
cities.append(city)
keys.append(key)
print(f"{city:<12}{key}")
found = cities[keys.index("zurich")]
print(f"Search 'zurich' -> {found}")
assert found == "Zürich"
assert "sao paulo" in keys and "asuncion" in keys
Output
Köln koln
Málaga malaga
Besançon besancon
Malmö malmo
São Paulo sao paulo
Zürich zurich
Genève geneve
Montréal montreal
Reykjavík reykjavik
Bogotá bogota
Göteborg goteborg
Asunción asuncion
Search 'zurich' -> Zürich

How it works:

  1. NFKD splits each accented letter into its base letter and a combining mark: ü becomes u + ◌̈.
  2. encode("ascii", "ignore") drops every non-ASCII code point, so the marks vanish and the base letters stay.
  3. decode() turns the ASCII bytes back into a str, and casefold() makes the key lowercase.
  4. keys.index("zurich") returns the position of the key in the list. The same position in cities holds the real spelling.

Alternative: keep the key for searching only. Every city in this file decomposes cleanly, but a city with ø or ł (for example Łódź) would lose letters: odz. For those, a hand-made table of replacements (ł → l) or the third-party package Unidecode gives better keys.

M02-C13 · Mask a user’s e-mail address in a log line

Section titled “M02-C13 · Mask a user’s e-mail address in a log line”
Core

Line 5 of data/logs/app.log ends with the user’s e-mail address. Before you share log lines in a ticket, mask the personal part of the address: keep its first character, replace the rest with *, and keep the domain. Print the masked line without its 24-character timestamp, so that it fits on one screen line.

Expected output
INFO [api] 172.16.4.9 POST /api/v1/predict 201 93ms user=m*******@example.org
Starter
log_line = (
"2024-05-01 08:08:39,278 INFO [api] 172.16.4.9 POST /api/v1/predict "
"201 93ms user=mei.chen@example.org"
)
# TODO: split off the e-mail after "user="
# TODO: split the e-mail at "@" and mask the local part
# TODO: rebuild and print the line
Hint 1

log_line.rpartition("user=") gives the text before the e-mail, the separator, and the e-mail.

Hint 2

"*" * n repeats the star n times. The local part mei.chen has 8 characters, so you need 7 stars.

Solution
log_line = (
"2024-05-01 08:08:39,278 INFO [api] 172.16.4.9 POST /api/v1/predict "
"201 93ms user=mei.chen@example.org"
)
before, sep, email = log_line.rpartition("user=")
local, at, domain = email.partition("@")
masked = local[0] + "*" * (len(local) - 1) + at + domain
print((before + sep + masked)[24:]) # skip the timestamp to fit the page
assert masked == "m*******@example.org"
assert len(masked) == len(email)
Output
INFO [api] 172.16.4.9 POST /api/v1/predict 201 93ms user=m*******@example.org

How it works:

  1. rpartition("user=") splits at the last user= and returns three strings. Joining them again gives the original line.
  2. partition("@") splits the address into the local part mei.chen, the @ and the domain example.org.
  3. local[0] keeps the first letter; "*" * (len(local) - 1) makes 7 stars, so the mask keeps the length.
  4. The domain stays readable, so a support engineer can still see which organization the user belongs to.

Alternative: if the masked length must not reveal the length of the name, use a fixed mask such as local[0] + "***". Module 09 shows how to mask every e-mail in a whole log file with a regular expression.

Challenge

Build a scorecard of the regions in data/sales.csv for a management report. For each region, show the 2023 and 2024 revenue, the change in USD with a sign and a separator, and the growth in percent with a sign. Put a centered title bar on top and a total row at the bottom. Keep every column width in a variable.

Expected output
=========== Regional scorecard 2023-2024 (USD) ============
Region 2023 2024 Change Growth
-----------------------------------------------------------
East 448,918.63 544,765.09 +95,846.46 +21.4%
South 409,501.07 482,265.00 +72,763.93 +17.8%
North 410,500.06 477,729.41 +67,229.35 +16.4%
West 376,669.83 446,174.74 +69,504.91 +18.5%
-----------------------------------------------------------
Total 1,645,589.59 1,950,934.24 +305,344.65 +18.6%
===========================================================
Starter
revenue_csv = """region,revenue_2023,revenue_2024
East,448918.63,544765.09
South,409501.07,482265.00
North,410500.06,477729.41
West,376669.83,446174.74"""
w_name, w_num, w_pct = 8, 14, 9
# TODO: compute the totals of both years
# TODO: print the title bar, the header, a separator, the rows, a separator, the total
Hint 1

The table width is w_name + 3 * w_num + w_pct. Center the title in it with a nested spec: f"{' Regional scorecard ':=^{width}}".

Hint 2

The change column needs sign, width, grouping and precision, in this order: :>+{w_num},.2f. Growth: :>+{w_pct}.1%.

Hint 3

Compute the totals in a first loop. In the second loop, compute change = r24 - r23 and growth = r24 / r23 - 1 for each row.

Solution
revenue_csv = """region,revenue_2023,revenue_2024
East,448918.63,544765.09
South,409501.07,482265.00
North,410500.06,477729.41
West,376669.83,446174.74"""
w_name, w_num, w_pct = 8, 14, 9
width = w_name + 3 * w_num + w_pct
rows = revenue_csv.splitlines()[1:]
total_23 = 0.0
total_24 = 0.0
for row in rows:
parts = row.split(",")
total_23 += float(parts[1])
total_24 += float(parts[2])
def line(name, r23, r24):
return (
f"{name:<{w_name}}{r23:>{w_num},.2f}{r24:>{w_num},.2f}"
f"{r24 - r23:>+{w_num},.2f}{r24 / r23 - 1:>+{w_pct}.1%}"
)
print(f"{' Regional scorecard 2023-2024 (USD) ':=^{width}}")
print(
f"{'Region':<{w_name}}{'2023':>{w_num}}{'2024':>{w_num}}"
f"{'Change':>{w_num}}{'Growth':>{w_pct}}"
)
print("-" * width)
for row in rows:
parts = row.split(",")
print(line(parts[0], float(parts[1]), float(parts[2])))
print("-" * width)
print(line("Total", total_23, total_24))
print("=" * width)
assert round(total_24, 2) == 1950934.24
assert width == 59
Output
=========== Regional scorecard 2023-2024 (USD) ============
Region 2023 2024 Change Growth
-----------------------------------------------------------
East 448,918.63 544,765.09 +95,846.46 +21.4%
South 409,501.07 482,265.00 +72,763.93 +17.8%
North 410,500.06 477,729.41 +67,229.35 +16.4%
West 376,669.83 446,174.74 +69,504.91 +18.5%
-----------------------------------------------------------
Total 1,645,589.59 1,950,934.24 +305,344.65 +18.6%
===========================================================

How it works:

  1. The first loop adds up both years. The total row needs them.
  2. width is computed from the column widths, so the title bar and the separators always match the table.
  3. The helper line() formats one row. A function defined with def is a named, reusable block of code; module 05 covers functions. Here it guarantees that the region rows and the total row use exactly the same specs.
  4. >+14,.2f reads: right-align, always show the sign, width 14, thousands separator, 2 decimals. A fall in revenue would show - automatically.
  5. All four regions grew; East grew fastest (+21.4%). The total growth is +18.6%, the headline number of the dataset.

Alternative: without a function, write the row f-string twice (once in the loop, once for the total). That works, but two copies of a long spec drift apart when you edit one of them. Moving a repeated spec into one place is the first step toward module 05.

M02-X02 · Match customers with search keys

Section titled “M02-X02 · Match customers with search keys”
Challenge

The CRM must stop creating duplicate customers. Two names are the same customer when they have the same match key: the name in “first last” order, with single spaces, no accents and case-folded. Build a key for every line of data/messy_names.txt and print, for each line, the first line with the same key. Then match four new sign-ups from a web form, typed without accents, to existing lines.

The lesson’s ASCII trick drops letters that are not “letter + accent” (ø, ł, ð, ı), so łukasz would become ukasz and never match lukasz. Translate these letters first.

Expected output
Line Raw line Match key First
1 ' josé GARCÍA ' jose garcia 1
2 "ZOË o'brien" zoe o'brien 2
3 'françois dupont' francois dupont 3
4 'Björk Guðmundsdóttir ' bjork gudmundsdottir 4
5 ' anna-lena MÜLLER' anna-lena muller 5
6 'SØREN kierkegaard' soren kierkegaard 6
7 ' mei chen' mei chen 7
8 'José García' jose garcia 1
9 "renée O'Connor " renee o'connor 9
10 'ÇAĞLA yılmaz' cagla yilmaz 10
11 ' łukasz nowak' lukasz nowak 11
12 'maría josé fernández' maria jose fernandez 12
13 "Zoë O'Brien" zoe o'brien 2
14 'jean-luc PICARD ' jean-luc picard 14
15 ' émile zola' emile zola 15
16 'NGUYỄN văn an' nguyen van an 16
17 'aoife ní bhriain' aoife ni bhriain 17
18 ' Ana Silva ' ana silva 18
19 "o'neill, PATRICK" patrick o'neill 19
20 'Dvořák antonín' dvorak antonin 20
20 lines, 18 distinct customers
Sign-up 'jose garcia' -> line 1: josé GARCÍA
Sign-up 'LUKASZ NOWAK' -> line 11: łukasz nowak
Sign-up 'Soren Kierkegaard' -> line 6: SØREN kierkegaard
Sign-up 'cagla yilmaz' -> line 10: ÇAĞLA yılmaz
Without the table: 'łukasz' -> 'ukasz'
Starter
import unicodedata
from pathlib import Path
raw_names = Path("data/messy_names.txt").read_text(encoding="utf-8").splitlines()
signups = ["jose garcia", "LUKASZ NOWAK", "Soren Kierkegaard", "cagla yilmaz"]
# TODO: a translation table for ø Ø ł Ł ð ı
# TODO: a match_key(text) function: collapse spaces, "last, first" -> "first last",
# translate, NFKD, drop non-ASCII, casefold
# TODO: one table row per line: number, raw line (NFC, with repr), key, first line
# TODO: one line per sign-up: the matching line number and its raw text
Hint 1

str.maketrans("øØłŁðı", "oOlLdi") maps each letter to a plain one. Apply it with translate() before NFKD.

Hint 2

Collect the keys in a list in file order. keys.index(key) returns the position of the first line with that key, so keys.index(key) + 1 is the first line number.

Hint 3

Define def match_key(text): and end it with return key, so the file lines and the sign-ups use exactly the same rules. Example 6 and M02-X01 show the pieces.

Solution
import unicodedata
from pathlib import Path
raw_names = Path("data/messy_names.txt").read_text(encoding="utf-8").splitlines()
signups = ["jose garcia", "LUKASZ NOWAK", "Soren Kierkegaard", "cagla yilmaz"]
special = str.maketrans("øØłŁðı", "oOlLdi") # letters NFKD cannot split
def match_key(text):
text = " ".join(text.split())
text = " ".join(reversed(text.split(", "))) # "last, first" -> "first last"
text = unicodedata.normalize("NFKD", text.translate(special))
return text.encode("ascii", "ignore").decode().casefold()
keys = []
for raw in raw_names:
keys.append(match_key(raw))
print(f"{'Line':>4} {'Raw line':<26}{'Match key':<24}{'First':>5}")
number = 0
for raw in raw_names:
number += 1
key = keys[number - 1]
shown = unicodedata.normalize("NFC", raw)
print(f"{number:>4} {shown!r:<26}{key:<24}{keys.index(key) + 1:>5}")
print(f"{len(keys)} lines, {len(set(keys))} distinct customers")
for typed in signups:
line = keys.index(match_key(typed)) + 1
print(f"Sign-up {typed!r:<21} -> line {line:>2}: {raw_names[line - 1].strip()}")
plain = unicodedata.normalize("NFKD", "łukasz").encode("ascii", "ignore").decode()
print(f"Without the table: 'łukasz' -> {plain!r}")
assert len(set(keys)) == 18
assert keys.index(keys[7]) == 0 and keys.index(keys[12]) == 1
Output
Line Raw line Match key First
1 ' josé GARCÍA ' jose garcia 1
2 "ZOË o'brien" zoe o'brien 2
3 'françois dupont' francois dupont 3
4 'Björk Guðmundsdóttir ' bjork gudmundsdottir 4
5 ' anna-lena MÜLLER' anna-lena muller 5
6 'SØREN kierkegaard' soren kierkegaard 6
7 ' mei chen' mei chen 7
8 'José García' jose garcia 1
9 "renée O'Connor " renee o'connor 9
10 'ÇAĞLA yılmaz' cagla yilmaz 10
11 ' łukasz nowak' lukasz nowak 11
12 'maría josé fernández' maria jose fernandez 12
13 "Zoë O'Brien" zoe o'brien 2
14 'jean-luc PICARD ' jean-luc picard 14
15 ' émile zola' emile zola 15
16 'NGUYỄN văn an' nguyen van an 16
17 'aoife ní bhriain' aoife ni bhriain 17
18 ' Ana Silva ' ana silva 18
19 "o'neill, PATRICK" patrick o'neill 19
20 'Dvořák antonín' dvorak antonin 20
20 lines, 18 distinct customers
Sign-up 'jose garcia' -> line 1: josé GARCÍA
Sign-up 'LUKASZ NOWAK' -> line 11: łukasz nowak
Sign-up 'Soren Kierkegaard' -> line 6: SØREN kierkegaard
Sign-up 'cagla yilmaz' -> line 10: ÇAĞLA yılmaz
Without the table: 'łukasz' -> 'ukasz'

How it works:

  1. match_key() is a function (module 05): one set of rules for the file and the sign-ups. If the two used different rules, equal names could get different keys.
  2. split() and join() collapse the spaces. split(", ") with reversed() puts o'neill, PATRICK in “first last” order.
  3. translate(special) turns ø, ł, ð and ı into o, l, d and i. NFKD then splits the remaining accented letters, and encode("ascii", "ignore") drops the accents only.
  4. casefold() removes the case, so GARCÍA, García and garcia all give garcia.
  5. keys.index(key) finds the first line with the same key. Lines 8 and 13 point to lines 1 and 2: these are the two duplicates. All other lines point to themselves.
  6. Each sign-up gets a key with the same function, and keys.index() finds its customer. LUKASZ NOWAK matches line 11 only because of the translation table. Without it, łukasz gives ukasz, as the last line shows.

Alternative: keys.index() raises a ValueError for a sign-up with no match, so this code works only when every sign-up exists. Module 03 tests if key in keys: first, and module 04 replaces the list with a dict from key to line number, which is also much faster for many customers.

M02-X03 · Detect the encoding of three exports

Section titled “M02-X03 · Detect the encoding of three exports”
Challenge

Three systems export the first supplier of data/legacy_latin1.csv (SUP01,Café Müller GmbH,...). System A writes latin-1, system B writes UTF-8 and system C writes UTF-8 with a BOM, but nobody told you which is which. Decode each export with three candidate encodings (utf-8, utf-8-sig, cp1252) and errors="replace", so no decode raises. Mark a result as OK when it starts with SUP01, and contains the known name Café Müller. Pick the first OK encoding for each export, and prove that all three exports hold the same text.

Expected output
Export Encoding OK Decoded text
system A utf-8 False 'SUP01,Caf� M�ller GmbH,K�ln,'
system A utf-8-sig False 'SUP01,Caf� M�ller GmbH,K�ln,'
system A cp1252 True 'SUP01,Café Müller GmbH,Köln,'
system B utf-8 True 'SUP01,Café Müller GmbH,Köln,'
system B utf-8-sig True 'SUP01,Café Müller GmbH,Köln,'
system B cp1252 False 'SUP01,Café Müller GmbH,Kö'
system C utf-8 False '\ufeffSUP01,Café Müller GmbH,Köln'
system C utf-8-sig True 'SUP01,Café Müller GmbH,Köln,'
system C cp1252 False 'SUP01,Café Müller GmbH,'
system A: 40 bytes, starts b'SUP0', detected cp1252
system B: 43 bytes, starts b'SUP0', detected utf-8
system C: 46 bytes, starts b'\xef\xbb\xbfS', detected utf-8-sig
Same text in all three: True
Starter
from pathlib import Path
line = Path("data/legacy_latin1.csv").read_bytes().splitlines()[1]
text = line.decode("latin-1")
exports = [line, text.encode("utf-8"), text.encode("utf-8-sig")]
labels = ["system A", "system B", "system C"]
candidates = ["utf-8", "utf-8-sig", "cp1252"]
known = "Café Müller"
# TODO: for each export and each candidate, decode with errors="replace",
# compute ok and print one row (show the first 28 characters with repr)
# TODO: pick the first OK candidate for each export
# TODO: print the size, the first 4 bytes and the detected encoding of each export
# TODO: check that the three exports decode to the same text
Hint 1

for n in range(3): runs its block with n equal to 0, 1 and 2, so exports[n] and labels[n] belong together. Module 03 covers range().

Hint 2

Collect the ok values of one export in a list oks. candidates[oks.index(True)] is the first candidate that worked.

Hint 3

Look at the rows that are not OK. � means invalid bytes for that encoding.  at the start means a BOM that the decoder kept. é and  are mojibake: UTF-8 bytes read as cp1252.

Solution
from pathlib import Path
line = Path("data/legacy_latin1.csv").read_bytes().splitlines()[1]
text = line.decode("latin-1")
exports = [line, text.encode("utf-8"), text.encode("utf-8-sig")]
labels = ["system A", "system B", "system C"]
candidates = ["utf-8", "utf-8-sig", "cp1252"]
known = "Café Müller"
print(f"{'Export':<10}{'Encoding':<11}{'OK':<7}Decoded text")
detected = []
for n in range(3):
oks = []
for encoding in candidates:
decoded = exports[n].decode(encoding, errors="replace")
ok = decoded.startswith("SUP01,") and known in decoded
oks.append(ok)
print(f"{labels[n]:<10}{encoding:<11}{ok!s:<7}{decoded[:28]!r}")
detected.append(candidates[oks.index(True)])
for n in range(3):
data = exports[n]
size = len(data)
print(f"{labels[n]}: {size} bytes, starts {data[:4]!r}, detected {detected[n]}")
texts = []
for n in range(3):
texts.append(exports[n].decode(detected[n]))
print("Same text in all three:", texts[0] == texts[1] == texts[2])
assert detected == ["cp1252", "utf-8", "utf-8-sig"]
Output
Export Encoding OK Decoded text
system A utf-8 False 'SUP01,Caf� M�ller GmbH,K�ln,'
system A utf-8-sig False 'SUP01,Caf� M�ller GmbH,K�ln,'
system A cp1252 True 'SUP01,Café Müller GmbH,Köln,'
system B utf-8 True 'SUP01,Café Müller GmbH,Köln,'
system B utf-8-sig True 'SUP01,Café Müller GmbH,Köln,'
system B cp1252 False 'SUP01,Café Müller GmbH,Kö'
system C utf-8 False '\ufeffSUP01,Café Müller GmbH,Köln'
system C utf-8-sig True 'SUP01,Café Müller GmbH,Köln,'
system C cp1252 False 'SUP01,Café Müller GmbH,'
system A: 40 bytes, starts b'SUP0', detected cp1252
system B: 43 bytes, starts b'SUP0', detected utf-8
system C: 46 bytes, starts b'\xef\xbb\xbfS', detected utf-8-sig
Same text in all three: True

How it works:

  1. errors="replace" turns every decode into a result you can inspect, instead of a crash. Module 06 shows the other way: try decode() and catch the UnicodeDecodeError.
  2. System A (latin-1): the single bytes \xe9, \xfc and \xf6 are invalid UTF-8, so both UTF-8 candidates show �. cp1252 reads them as é, ü and ö.
  3. System B (UTF-8): utf-8 works. utf-8-sig also works, because it removes a BOM only if there is one. cp1252 gives mojibake (Café).
  4. System C (UTF-8 with BOM): plain utf-8 keeps the BOM as , so the text does not start with SUP01,. utf-8-sig removes it. cp1252 shows the BOM bytes as .
  5. The order of the candidates matters. The strictest encoding comes first, because cp1252 almost never fails: it would “succeed” on system B with garbled text if the known-name check were missing.
  6. The sizes tell the same story: 40 bytes in latin-1, 3 more in UTF-8 (one extra byte each for é, ü, ö) and 3 more for the BOM.

Alternative: the third-party package charset-normalizer (used by requests) guesses an encoding from the bytes alone. A guess on a short text is often wrong, so keep a known-value check like the one above in any pipeline.

M02-X04 · Parse API log lines into a request table

Section titled “M02-X04 · Parse API log lines into a request table”
Challenge

Five API request lines from data/logs/app.log are below. Parse each one into time, method, path, status, duration and user, and print an aligned table. Cut long paths to 24 characters, mask the e-mail as in M02-C13, and end with the mean duration. Each message has the form <ip> <METHOD> <path> <status> <ms>ms user=<email>.

Expected output
Time Method Path Status ms User
----------------------------------------------------------------------------
08:04:01 GET /api/v1/reports/2024-04 200 87 p*********@example.com
08:08:01 GET /api/v1/products?page=3 200 88 p*********@example.com
08:08:39 POST /api/v1/predict 201 93 m*******@example.org
08:16:42 GET /api/v1/products?page=2 200 31 p*********@example.com
08:17:50 GET /api/v1/products?page=3 200 42 d**********@example.net
----------------------------------------------------------------------------
5 requests, mean duration 68.2 ms
Starter
log_text = """\
2024-05-01 08:04:01,354 INFO [api] 10.0.3.17 GET /api/v1/reports/2024-04 200 87ms user=priya.nair@example.com
2024-05-01 08:08:01,234 INFO [api] 10.0.3.17 GET /api/v1/products?page=3 200 88ms user=priya.nair@example.com
2024-05-01 08:08:39,278 INFO [api] 172.16.4.9 POST /api/v1/predict 201 93ms user=mei.chen@example.org
2024-05-01 08:16:42,288 INFO [api] 203.0.113.45 GET /api/v1/products?page=2 200 31ms user=priya.nair@example.com
2024-05-01 08:17:50,978 INFO [api] 192.168.1.24 GET /api/v1/products?page=3 200 42ms user=diego.ramos@example.net"""
# TODO: for each line, slice the time and partition off the message after "] "
# TODO: split the message into its six parts
# TODO: print the header, one row per request and the mean duration
Hint 1

The clock time is line[11:19]. line.partition("] ") gives the message as its third part.

Hint 2

message.split() gives six parts: ip, method, path, status, duration, user. removesuffix("ms") and removeprefix("user=") clean the last two.

Hint 3

Use a precision to cut the path: :<24.24 pads to 24 and cuts at 24 characters.

Solution
log_text = """\
2024-05-01 08:04:01,354 INFO [api] 10.0.3.17 GET /api/v1/reports/2024-04 200 87ms \
user=priya.nair@example.com
2024-05-01 08:08:01,234 INFO [api] 10.0.3.17 GET /api/v1/products?page=3 200 88ms \
user=priya.nair@example.com
2024-05-01 08:08:39,278 INFO [api] 172.16.4.9 POST /api/v1/predict 201 93ms \
user=mei.chen@example.org
2024-05-01 08:16:42,288 INFO [api] 203.0.113.45 GET /api/v1/products?page=2 200 31ms \
user=priya.nair@example.com
2024-05-01 08:17:50,978 INFO [api] 192.168.1.24 GET /api/v1/products?page=3 200 42ms \
user=diego.ramos@example.net"""
header = f"{'Time':<10}{'Method':<7}{'Path':<25}{'Status':>6}{'ms':>6} User"
print(header)
print("-" * 76)
total_ms = 0
count = 0
for line in log_text.splitlines():
clock = line[11:19]
message = line.partition("] ")[2]
ip, method, path, status, duration, user = message.split()
ms = int(duration.removesuffix("ms"))
local, at, domain = user.removeprefix("user=").partition("@")
masked = local[0] + "*" * (len(local) - 1) + at + domain
print(f"{clock:<10}{method:<7}{path:<24.24} {status:>6}{ms:>6} {masked}")
total_ms += ms
count += 1
print("-" * 76)
print(f"{count} requests, mean duration {total_ms / count:.1f} ms")
assert count == 5 and total_ms == 341
Output
Time Method Path Status ms User
----------------------------------------------------------------------------
08:04:01 GET /api/v1/reports/2024-04 200 87 p*********@example.com
08:08:01 GET /api/v1/products?page=3 200 88 p*********@example.com
08:08:39 POST /api/v1/predict 201 93 m*******@example.org
08:16:42 GET /api/v1/products?page=2 200 31 p*********@example.com
08:17:50 GET /api/v1/products?page=3 200 42 d**********@example.net
----------------------------------------------------------------------------
5 requests, mean duration 68.2 ms

How it works:

  1. The backslash at the end of a line inside the triple-quoted string joins it with the next line, so each log line stays one line but the code stays under 88 characters. The \ right after """ drops the first line break.
  2. The timestamp has fixed positions: line[11:19] is HH:MM:SS.
  3. partition("] ") cuts once after the component name; the third part is the message.
  4. message.split() returns six parts, and ip, method, path, status, duration, user = ... gives each one a name. This is called unpacking; module 04 covers it.
  5. :<24.24 pads short paths to 24 characters and cuts long ones at 24, so /api/v1/products?page=3 and the longer report path fit the column.
  6. The mean is 341 ms / 5 requests = 68.2 ms.

Alternative: module 09 parses the same lines with one regular expression, re.match(r"(\S+) (\S+) (\S+) (\d+) (\d+)ms user=(\S+)", message), which also rejects lines that do not have the expected shape.

M02-X05 · Interpret: shares that add up to 101%

Section titled “M02-X05 · Interpret: shares that add up to 101%”
Challenge

Interpret a result: a dashboard shows the revenue share of each region in data/sales.csv, rounded to whole percent. A manager notices that the shares add up to 101%.

east, south, north, west = 993683.72, 891766.07, 888229.47, 822844.57
total = east + south + north + west
print(f"East {east / total:.0%}, South {south / total:.0%}, ", end="")
print(f"North {north / total:.0%}, West {west / total:.0%}")
print("Sum of the shown shares: 28 + 25 + 25 + 23 =", 28 + 25 + 25 + 23)
Output
East 28%, South 25%, North 25%, West 23%
Sum of the shown shares: 28 + 25 + 25 + 23 = 101

Explain why the sum is 101 although the real shares add up to exactly 100%. Then print a version that shows one decimal per share, the sum of the real shares and the sum of the shown values:

Expected output
East 27.6%, South 24.8%, North 24.7%, West 22.9%
Precise: 27.629% 24.795% 24.697% 22.879%
Sum of the real shares: 100.0%
Sum of the shown values: 100.0%
Starter
east, south, north, west = 993683.72, 891766.07, 888229.47, 822844.57
total = east + south + north + west
# TODO: compute the four shares
# TODO: print them with one decimal
# TODO: print the sum of the real shares and the sum of the rounded, shown values
Hint 1

Print each share with more decimals, for example :.3%. How far is each one from its rounded value?

Hint 2

Each share is rounded on its own. The rounding errors do not cancel out. To get the shown values as numbers, use round(share * 100, 1).

Solution
east, south, north, west = 993683.72, 891766.07, 888229.47, 822844.57
total = east + south + north + west
s_east, s_south = east / total, south / total
s_north, s_west = north / total, west / total
print(f"East {s_east:.1%}, South {s_south:.1%}, North {s_north:.1%}, West {s_west:.1%}")
print(f"Precise: {s_east:.3%} {s_south:.3%} {s_north:.3%} {s_west:.3%}")
real_sum = s_east + s_south + s_north + s_west
shown_sum = (
round(s_east * 100, 1) + round(s_south * 100, 1)
+ round(s_north * 100, 1) + round(s_west * 100, 1)
)
print(f"Sum of the real shares: {real_sum:.1%}")
print(f"Sum of the shown values: {shown_sum:.1f}%")
assert round(real_sum, 9) == 1
assert round(shown_sum, 1) == 100.0
Output
East 27.6%, South 24.8%, North 24.7%, West 22.9%
Precise: 27.629% 24.795% 24.697% 22.879%
Sum of the real shares: 100.0%
Sum of the shown values: 100.0%

How it works:

  1. Interpretation: the precise shares are 27.629%, 24.795%, 24.697% and 22.879%. Rounded to whole numbers, East gains 0.37 points, South 0.21, North 0.30 and West 0.12. These errors all go upward and add up to 1.0 point, so the shown values sum to 101.
  2. The real shares always add up to 100%; only the displayed values do not. No calculation is wrong.
  3. With one decimal, each error is at most 0.05 points. Here the shown values happen to add up to 100.0. With more categories, a sum of 99.9 or 100.1 can still appear.
  4. round(s * 100, 1) turns each share into the number that the report shows, so shown_sum adds what the reader sees.

Alternative: reports that must add up to exactly 100 use the largest remainder method: round every share down, then give the missing points to the shares with the largest remainders. Otherwise, add a footnote: “Shares may not add up to 100% because of rounding.”