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:
- Read the task and the expected output (or the acceptance criteria).
- Copy the starter code into a script (for example
exercise.py) in your project folder, next to thedata/folder. Replace each to-do comment with your code. - Run the script with
python exercise.py. Compare your output with the expected output. - 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
Section titled “Warm-up”M02-W01 · Slice an order date
Section titled “M02-W01 · Slice an order date”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.
Year 2023, month 1, day 4order_date = "2023-01-04"# TODO: slice out the year, month and day and convert them to int# TODO: print the sentenceHint 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] == "-"Year 2023, month 1, day 4How it works:
order_date[:4]takes indexes 0 to 3:'2023'.order_date[5:7]takes indexes 5 and 6:'01'. The stop index 7 (the second dash) is excluded.order_date[8:]takes everything from index 8 to the end:'04'.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])}")Year 2023, month 1, day 4M02-W02 · Predict the output: index and slice
Section titled “M02-W02 · Predict the output: index and slice”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.
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 itHint 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) == 16assert product[:8] + product[8:] == productW sWirelessEarbudsEarWesEbs1 ' 'How it works:
product[0]is the first characterW;product[-1]is the last,s.[:8]takes indexes 0 to 7:Wireless. Index 8 is the space.[9:]starts after the space:Earbuds.[-7:-4]takes indexes 9, 10 and 11 (−7, −6 and −5), because −4 is excluded:Ear.[::3]takes every third character from index 0:W,e,s,E,b,s.[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])Wireless Earbuds EarM02-W03 · Clean region labels
Section titled “M02-W03 · Clean region labels”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.
' north' -> 'North''SOUTH ' -> 'South'' eAsT ' -> 'East'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")' north' -> 'North''SOUTH ' -> 'South'' eAsT ' -> 'East'How it works:
strip()removes whitespace at both ends and returns a new string.title()makes the first letter of each word upper case and the rest lower case.eAsTbecomesEast.!rin a replacement field formats the value withrepr(), 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”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}]")[ san francisco ]Change the code so that it prints:
[San Francisco]store_city = " san francisco "store_city.strip() # TODO: fix these two linesstore_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"[San Francisco]How it works:
- A string method never changes the string. It returns a new one.
- The buggy code threw both results away, so
store_citykept its original value. store_city.strip().title()runsstrip()first and callstitle()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.
M02-W05 · Format a price list
Section titled “M02-W05 · Format a price list”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.
Wireless Earbuds 79.9955-inch 4K Smart TV 1,299.00Running Socks 3-Pack 14.99name_1, price_1 = "Wireless Earbuds", 79.99name_2, price_2 = "55-inch 4K Smart TV", 1299.0name_3, price_3 = "Running Socks 3-Pack", 14.99# TODO: print one aligned line per productHint 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.99name_2, price_2 = "55-inch 4K Smart TV", 1299.0name_3, price_3 = "Running Socks 3-Pack", 14.99line_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) == 32Wireless Earbuds 79.9955-inch 4K Smart TV 1,299.00Running Socks 3-Pack 14.99How it works:
:<22pads each name with spaces on the right to 22 characters.:>10,.2fpads each price on the left to 10 characters, adds the comma in1,299.00and always shows 2 decimals.- 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().
M02-W06 · Percentages and signs
Section titled “M02-W06 · Percentages and signs”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.
Churn rate: 19.3%East growth: +21.4%Discount: 5%churn_rate = 0.1926east_2023 = 448918.63east_2024 = 544765.09discount = 0.05# TODO: compute the growth as a fraction and print the three linesHint 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.1926east_2023 = 448918.63east_2024 = 544765.09discount = 0.05growth = east_2024 / east_2023 - 1print(f"Churn rate: {churn_rate:.1%}")print(f"East growth: {growth:+.1%}")print(f"Discount: {discount:.0%}")assert 0.21 < growth < 0.22assert f"{-growth:+.1%}" == "-21.4%"Churn rate: 19.3%East growth: +21.4%Discount: 5%How it works:
%multiplies the value by 100 and adds a percent sign..1keeps one decimal.+shows the sign of every number, so a rise reads+21.4%and a fall reads-21.4%(the second assert)..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.
M02-W07 · Split and join a store record
Section titled “M02-W07 · Split and join a store record”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.
Chicago (S01), North region, 2,850 m², opened 2009S01,Chicago,North,2850,2009-03-14record = "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 lineHint 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) == 5assert ",".join(fields).split(",") == fieldsChicago (S01), North region, 2,850 m², opened 2009S01,Chicago,North,2850,2009-03-14How it works:
split("|")cuts at each|and returns['S01', 'Chicago', 'North', '2850', '2009-03-14'].fields[4][:4]first takes the date string, then slices its first 4 characters.int(fields[3])makes a number, so:,can add the separator.",".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”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.
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 itHint 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") == cityassert len(city.encode("utf-8")) - len(city) == 1454b'K\xc3\xb6ln'246 TrueHow it works:
- The string has 4 characters:
K,ö,l,n. - UTF-8 writes
K,landnas 1 byte each andöas 2 bytes (c3 b6): 5 bytes. - latin-1 writes every character as exactly 1 byte: 4 bytes.
- The bytes print as
b'K\xc3\xb6ln': the ASCII letters stay readable, the two bytes oföshow as hex. - The code point of
öis 246, andchr(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.
M02-C01 · Parse a raw sales line
Section titled “M02-C01 · Parse a raw sales line”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.
O003612 2023-08-16 South | Cotton Bed Sheet Set | 1 x 69.99Revenue 69.99 matches file: Trueraw = "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 linesHint 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) == 13assert region == "South" and product == "Cotton Bed Sheet Set"O003612 2023-08-16 South | Cotton Bed Sheet Set | 1 x 69.99Revenue 69.99 matches file: TrueHow it works:
split(",")gives 13 fields, one per column.strip().title()turns' South 'into'South'.split()cuts the product name into words and drops the extra space;" ".join()puts the words back with single spaces.removeprefix("$")leaves'69.99', whichfloat()can read.- 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 fromround()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”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("$"))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.
1149.0 1,149.00price_text = "$1,149.00"unit_price = float(price_text.strip("$")) # TODO: fix this lineprint(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.0assert float("$79.99".removeprefix("$").replace(",", "")) == 79.991149.0 1,149.00How it works:
removeprefix("$")gives'1,149.00'.replace(",", "")gives'1149.00', whichfloat()reads as1149.0.- The f-string adds the separator back for display only:
1,149.00. - 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)))1149.0M02-C03 · Aligned table of revenue by region
Section titled “M02-C03 · Aligned table of revenue by region”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.
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%regions_csv = """East,544765.09South,482265.00North,477729.41West,446174.74"""# TODO: compute the total with a loop# TODO: print the header, a separator, one row per region, a separator and the totalHint 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.09South,482265.00North,477729.41West,446174.74"""lines = regions_csv.splitlines()total = 0.0for 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.24assert len(header) == 32Region 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:
- The first loop adds each revenue to
total. The share column needs the total first. - The header uses the same widths and alignments as the rows: the text header
Revenue (USD)is right-aligned like the numbers below it. "-" * len(header)makes a separator exactly as wide as the table.- 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”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.
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 itHint 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[007][ S01][**S01**][1,299.00][5%][-0.00] [0.00][2.67] [0.12][Noise-Canc] [1_234_567]How it works:
03d: width 3, padded with zeros.>6: right-aligned in 6 characters, so 3 spaces come first.*^7: centered in 7 characters with*as the fill: 2 stars on each side.,.2f: thousands separator and 2 decimals, also for anint..0%: 0.05 × 100 = 5, no decimals.-0.004rounds to-0.00. Thezoption turns negative zero into0.00.2.675is really 2.67499…, so it rounds down.0.125is an exact tie and rounds to the even digit 2..10on 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”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.
Zoë O'Brien (11) vs Zoë O'Brien (12): FalseAfter NFC: 11 vs 11: Trueimport unicodedatafrom 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 againHint 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 unicodedatafrom 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_bassert nfc_a == nfc_b == "Zoë O'Brien"Zoë O'Brien (11) vs Zoë O'Brien (12): FalseAfter NFC: 11 vs 11: TrueHow it works:
- Line 2 is
"ZOË o'brien". Title case givesZoë O'Brienwith a composedë(one code point). - Line 13 is in NFD form: its
ëisefollowed by a combining diaeresis. It looks the same but has 12 code points. ==compares code points, so the two strings differ.- 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”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")UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 49: invalid continuation byteFix it so that it prints:
supplier_id,supplier,city,country,sinceSUP01,Café Müller GmbH,Köln,Germany,2015SUP02,Textiles Señora,Málaga,Spain,201712 suppliersfrom pathlib import Path
text = Path("data/legacy_latin1.csv").read_text(encoding="utf-8") # TODO: fixlines = 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) == 13supplier_id,supplier,city,country,sinceSUP01,Café Müller GmbH,Köln,Germany,2015SUP02,Textiles Señora,Málaga,Spain,201712 suppliersHow it works:
- The error says that byte 49 (
0xe9) is not valid UTF-8 at that place. In latin-1,0xe9isé. encoding="latin-1"decodes each byte as one character, soCafé Müller,KölnandMálagaappear correctly.- 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])SUP01,Café Müller GmbH,Köln,Germany,2015SUP01,Café Müller GmbH,Köln,Germany,2015M02-C07 · Repair mojibake
Section titled “M02-C07 · Repair mojibake”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.
Köln -> KölnMálaga -> MálagaZürich -> ZürichSão Paulo -> São Paulogarbled = ["Köln", "Málaga", "Zürich", "São Paulo"]# TODO: for each city, undo the wrong decoding and print both valuesHint 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"]Köln -> KölnMálaga -> MálagaZürich -> ZürichSão Paulo -> São PauloHow it works:
- In UTF-8,
öis the two bytesc3 b6. Read as latin-1, those bytes are the two charactersÃand¶. encode("latin-1")turns each garbled character back into its byte, so you getc3 b6again.decode("utf-8")reads the two bytes as one character:ö.- Mojibake strings are longer than the real ones (
Kölnhas 5 characters,Köln4), 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.
M02-C08 · Interpret: a misaligned table
Section titled “M02-C08 · Interpret: a misaligned table”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}")Björk Guðmundsdóttir 4José García 8NGUYỄN văn an 16Explain why the José García row is misaligned. Then fix the code so that every row lines up:
Björk Guðmundsdóttir 4José García 8NGUYỄN văn an 16from pathlib import Path
lines = Path("data/messy_names.txt").read_text(encoding="utf-8").splitlines()# TODO: fix the alignment of the three rowsprint(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 unicodedatafrom 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) == 11Björk Guðmundsdóttir 4José García 8NGUYỄN văn an 16How it works:
- Interpretation:
José Garcíaon line 8 is stored in NFD form: 11 visible letters, but 13 code points, becauseéandíare each a letter plus a combining accent. - The spec
:<24pads 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. - 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”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.
chef's knife set title(): Chef'S Knife Set catalog: Chef's Knife Set55-inch 4k smart tv title(): 55-Inch 4K Smart Tv catalog: 55-inch 4K Smart TVNON-SLIP yoga mat title(): Non-Slip Yoga Mat catalog: Non-Slip Yoga Matfrom 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 textHint 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"]chef's knife set title(): Chef'S Knife Set catalog: Chef's Knife Set55-inch 4k smart tv title(): 55-Inch 4K Smart Tv catalog: 55-inch 4K Smart TVNON-SLIP yoga mat title(): Non-Slip Yoga Mat catalog: Non-Slip Yoga MatHow it works:
title()starts a new word after every non-letter. It givesChef'S(after the apostrophe),InchandTv(it lowercases the rest of each word). Only the yoga mat comes out right.- 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.
- 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”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.
Lines: 1,200Lines with a messy product name: 95 (7.9%)Distinct spellings: 90 -> 30import csvfrom 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 linesHint 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 csvfrom 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 = 0for row in rows: raw = row[7] clean = " ".join(raw.split()) raw_names.append(raw) clean_names.append(clean) changed += raw != cleanprint(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 == 95assert len(set(clean_names)) == 30Lines: 1,200Lines with a messy product name: 95 (7.9%)Distinct spellings: 90 -> 30How it works:
csv.reader()splits each line correctly, even the lines with quoted dates and prices." ".join(raw.split())removes spaces at both ends and collapses double spaces inside.raw != cleanisTruefor a messy name. Adding aboolto anintadds 1 or 0, sochangedcounts the messy lines.- 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”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.16share = 0.130205line = ( "Store " + store_id + " (" + city + "): " + str(round(revenue, 1)) + " USD, " + str(round(share * 100, 1)) + "% of total")print(line)Store S07 (New York): 468290.2 USD, 13.0% of totalThe refactored line must show the revenue with a separator and 2 decimals:
Store S07 (New York): 468,290.16 USD, 13.0% of totalstore_id = "S07"city = "New York"revenue = 468290.16share = 0.130205# TODO: build the same line with one f-stringHint 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.16share = 0.130205line = f"Store {store_id} ({city}): {revenue:,.2f} USD, {share:.1%} of total"print(line)assert "468,290.16" in lineassert line.endswith("13.0% of total")Store S07 (New York): 468,290.16 USD, 13.0% of totalHow it works:
- The f-string shows the shape of the final line at a glance: text and fields in their real order.
- f-strings convert values for you, so every
str()call disappears. :,.2fformats the revenue with a separator and exactly 2 decimals.round(revenue, 1)had dropped a digit, andround()never adds trailing zeros.:.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))Store S01 (Chicago): 406,532.46 USD, 11.3% of totalM02-C12 · Accent-free search keys for supplier cities
Section titled “M02-C12 · Accent-free search keys for supplier cities”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.
Köln kolnMálaga malagaBesançon besanconMalmö malmoSão Paulo sao pauloZürich zurichGenève geneveMontréal montrealReykjavík reykjavikBogotá bogotaGöteborg goteborgAsunción asuncionSearch 'zurich' -> Zürichimport unicodedatafrom 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 unicodedatafrom 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 keysKöln kolnMálaga malagaBesançon besanconMalmö malmoSão Paulo sao pauloZürich zurichGenève geneveMontréal montrealReykjavík reykjavikBogotá bogotaGöteborg goteborgAsunción asuncionSearch 'zurich' -> ZürichHow it works:
- NFKD splits each accented letter into its base letter and a combining mark:
übecomesu+◌̈. encode("ascii", "ignore")drops every non-ASCII code point, so the marks vanish and the base letters stay.decode()turns the ASCII bytes back into astr, andcasefold()makes the key lowercase.keys.index("zurich")returns the position of the key in the list. The same position incitiesholds 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”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.
INFO [api] 172.16.4.9 POST /api/v1/predict 201 93ms user=m*******@example.orglog_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 lineHint 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 + domainprint((before + sep + masked)[24:]) # skip the timestamp to fit the pageassert masked == "m*******@example.org"assert len(masked) == len(email)INFO [api] 172.16.4.9 POST /api/v1/predict 201 93ms user=m*******@example.orgHow it works:
rpartition("user=")splits at the lastuser=and returns three strings. Joining them again gives the original line.partition("@")splits the address into the local partmei.chen, the@and the domainexample.org.local[0]keeps the first letter;"*" * (len(local) - 1)makes 7 stars, so the mask keeps the length.- 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
Section titled “Challenge”M02-X01 · A regional scorecard
Section titled “M02-X01 · A regional scorecard”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.
=========== 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%===========================================================revenue_csv = """region,revenue_2023,revenue_2024East,448918.63,544765.09South,409501.07,482265.00North,410500.06,477729.41West,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 totalHint 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_2024East,448918.63,544765.09South,409501.07,482265.00North,410500.06,477729.41West,376669.83,446174.74"""w_name, w_num, w_pct = 8, 14, 9width = w_name + 3 * w_num + w_pctrows = revenue_csv.splitlines()[1:]
total_23 = 0.0total_24 = 0.0for 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.24assert width == 59=========== 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:
- The first loop adds up both years. The total row needs them.
widthis computed from the column widths, so the title bar and the separators always match the table.- The helper
line()formats one row. A function defined withdefis 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. >+14,.2freads: right-align, always show the sign, width 14, thousands separator, 2 decimals. A fall in revenue would show-automatically.- 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”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.
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 2020 lines, 18 distinct customersSign-up 'jose garcia' -> line 1: josé GARCÍASign-up 'LUKASZ NOWAK' -> line 11: łukasz nowakSign-up 'Soren Kierkegaard' -> line 6: SØREN kierkegaardSign-up 'cagla yilmaz' -> line 10: ÇAĞLA yılmazWithout the table: 'łukasz' -> 'ukasz'import unicodedatafrom 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 textHint 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 unicodedatafrom 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 = 0for 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)) == 18assert keys.index(keys[7]) == 0 and keys.index(keys[12]) == 1Line 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 2020 lines, 18 distinct customersSign-up 'jose garcia' -> line 1: josé GARCÍASign-up 'LUKASZ NOWAK' -> line 11: łukasz nowakSign-up 'Soren Kierkegaard' -> line 6: SØREN kierkegaardSign-up 'cagla yilmaz' -> line 10: ÇAĞLA yılmazWithout the table: 'łukasz' -> 'ukasz'How it works:
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.split()andjoin()collapse the spaces.split(", ")withreversed()putso'neill, PATRICKin “first last” order.translate(special)turnsø,ł,ðandıintoo,l,dandi. NFKD then splits the remaining accented letters, andencode("ascii", "ignore")drops the accents only.casefold()removes the case, soGARCÍA,Garcíaandgarciaall givegarcia.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.- Each sign-up gets a key with the same function, and
keys.index()finds its customer.LUKASZ NOWAKmatches line 11 only because of the translation table. Without it,łukaszgivesukasz, 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”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.
Export Encoding OK Decoded textsystem 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 cp1252system B: 43 bytes, starts b'SUP0', detected utf-8system C: 46 bytes, starts b'\xef\xbb\xbfS', detected utf-8-sigSame text in all three: Truefrom 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 textHint 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"]Export Encoding OK Decoded textsystem 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 cp1252system B: 43 bytes, starts b'SUP0', detected utf-8system C: 46 bytes, starts b'\xef\xbb\xbfS', detected utf-8-sigSame text in all three: TrueHow it works:
errors="replace"turns every decode into a result you can inspect, instead of a crash. Module 06 shows the other way: trydecode()and catch theUnicodeDecodeError.- System A (latin-1): the single bytes
\xe9,\xfcand\xf6are invalid UTF-8, so both UTF-8 candidates show�. cp1252 reads them asé,üandö. - System B (UTF-8):
utf-8works.utf-8-sigalso works, because it removes a BOM only if there is one. cp1252 gives mojibake (Café). - System C (UTF-8 with BOM): plain
utf-8keeps the BOM as, so the text does not start withSUP01,.utf-8-sigremoves it. cp1252 shows the BOM bytes as. - 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.
- 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”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>.
Time Method Path Status ms User----------------------------------------------------------------------------08:04:01 GET /api/v1/reports/2024-04 200 87 p*********@example.com08:08:01 GET /api/v1/products?page=3 200 88 p*********@example.com08:08:39 POST /api/v1/predict 201 93 m*******@example.org08:16:42 GET /api/v1/products?page=2 200 31 p*********@example.com08:17:50 GET /api/v1/products?page=3 200 42 d**********@example.net----------------------------------------------------------------------------5 requests, mean duration 68.2 mslog_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.com2024-05-01 08:08:01,234 INFO [api] 10.0.3.17 GET /api/v1/products?page=3 200 88ms user=priya.nair@example.com2024-05-01 08:08:39,278 INFO [api] 172.16.4.9 POST /api/v1/predict 201 93ms user=mei.chen@example.org2024-05-01 08:16:42,288 INFO [api] 203.0.113.45 GET /api/v1/products?page=2 200 31ms user=priya.nair@example.com2024-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 durationHint 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.com2024-05-01 08:08:01,234 INFO [api] 10.0.3.17 GET /api/v1/products?page=3 200 88ms \user=priya.nair@example.com2024-05-01 08:08:39,278 INFO [api] 172.16.4.9 POST /api/v1/predict 201 93ms \user=mei.chen@example.org2024-05-01 08:16:42,288 INFO [api] 203.0.113.45 GET /api/v1/products?page=2 200 31ms \user=priya.nair@example.com2024-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 = 0count = 0for 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 += 1print("-" * 76)print(f"{count} requests, mean duration {total_ms / count:.1f} ms")assert count == 5 and total_ms == 341Time Method Path Status ms User----------------------------------------------------------------------------08:04:01 GET /api/v1/reports/2024-04 200 87 p*********@example.com08:08:01 GET /api/v1/products?page=3 200 88 p*********@example.com08:08:39 POST /api/v1/predict 201 93 m*******@example.org08:16:42 GET /api/v1/products?page=2 200 31 p*********@example.com08:17:50 GET /api/v1/products?page=3 200 42 d**********@example.net----------------------------------------------------------------------------5 requests, mean duration 68.2 msHow it works:
- 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. - The timestamp has fixed positions:
line[11:19]isHH:MM:SS. partition("] ")cuts once after the component name; the third part is the message.message.split()returns six parts, andip, method, path, status, duration, user = ...gives each one a name. This is called unpacking; module 04 covers it.:<24.24pads short paths to 24 characters and cuts long ones at 24, so/api/v1/products?page=3and the longer report path fit the column.- 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%”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.57total = east + south + north + westprint(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)East 28%, South 25%, North 25%, West 23%Sum of the shown shares: 28 + 25 + 25 + 23 = 101Explain 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:
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%east, south, north, west = 993683.72, 891766.07, 888229.47, 822844.57total = 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 valuesHint 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.57total = east + south + north + wests_east, s_south = east / total, south / totals_north, s_west = north / total, west / totalprint(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_westshown_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) == 1assert round(shown_sum, 1) == 100.0East 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:
- 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.
- The real shares always add up to 100%; only the displayed values do not. No calculation is wrong.
- 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.
round(s * 100, 1)turns each share into the number that the report shows, soshown_sumadds 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.”