02. Strings and text
Most raw data is text. A CSV file is text. A product name, a region label, a date such as 2023-01-04 and a price such as $1,299.00 all arrive as strings before they become numbers or categories. Reports go out as text too. This module teaches you to take text apart, clean it, and put numbers back into clear, aligned report lines.
What you will learn
Section titled “What you will learn”- Read single characters with indexing and ranges of characters with slicing, and explain why strings are immutable.
- Clean, search, split and join text with string methods, and chain methods into one cleaning step.
- Format numbers for reports with f-strings and the format spec mini-language: width, alignment, fill, signs, thousands separators, precision and percentages.
- Print an aligned text table of sales figures with headers, separators and a total row.
- Explain the difference between
strandbytes, encode and decode text, and fix aUnicodeDecodeErrorand garbled text. - Clean messy names and product and region labels: stray spaces, inconsistent case, accents and Unicode normalization.
Prerequisites
Section titled “Prerequisites”- 01. Python basics: variables, the five basic types,
print(), type conversion and simple f-strings. - The course datasets in a
data/folder inside your project: Get the data.
Concepts
Section titled “Concepts”Strings are sequences of characters
Section titled “Strings are sequences of characters”A string (str) is text: a sequence of characters in a fixed order. A character is one letter, digit, space or symbol, such as P, 7, or €. You write a string literal between single quotes, double quotes, or three quotes for text that spans several lines.
product = "Chef's Knife Set" # double quotes: the apostrophe needs no escapestore = 'S01' # single quotes make the same kind of stringnote = """Line 1 of a note.Line 2 of the same note."""print(product, store)print(note)print(len(product), len(store), len(""))Chef's Knife Set S01Line 1 of a note.Line 2 of the same note.16 3 0The built-in function len() returns the number of characters. Spaces and punctuation count. The empty string "" has length 0.
Some characters cannot be typed directly inside quotes. An escape sequence is a backslash \ followed by a code that stands for one such character:
| Escape | Character | Typical use |
|---|---|---|
\n |
line break (newline) | the end of each line in a text file |
\t |
tab | columns in a tab-separated file |
\\ |
one backslash | Windows paths |
\', \" |
a quote inside the same kind of quotes | 'Chef\'s Knife Set' |
\u00e9 |
the character with that Unicode number (é) |
characters you cannot type |
print() shows the characters. The built-in function repr() shows the string as you would write it in code, with quotes and escapes. Use repr() whenever you clean data: it makes invisible characters visible.
raw_line = " North\t2850\n"print(raw_line)print(repr(raw_line))print(len(raw_line)) North 2850
' North\t2850\n'13The printed line looks like North 2850 with some spaces. repr() shows the truth: two leading spaces, a tab and a line break. That is 13 characters, not 10.
A raw string has the letter r before the quote. In a raw string, a backslash is just a backslash. Use raw strings for Windows paths and for regular expressions (module 09):
print("C:\\data\\new_sales.csv")print(r"C:\data\new_sales.csv")C:\data\new_sales.csvC:\data\new_sales.csvThe keyword in tests if one string appears inside another. A string that appears inside another string is a substring.
>>> "Smart TV" in "55-inch 4K Smart TV"True>>> "smart tv" in "55-inch 4K Smart TV"False>>> "Books" not in "Electronics"TrueThe test is case-sensitive: s and S are different characters.
Indexing: one character by position
Section titled “Indexing: one character by position”Each character has a position, its index. Python counts from 0, so the first character has index 0. This is called zero-based indexing. Put the index in square brackets after the string.
index: 0 1 2 3 4 5 6 string: O 0 0 0 0 5 1 negative: -7 -6 -5 -4 -3 -2 -1A negative index counts from the end: -1 is the last character, -2 the one before it. Negative indexes save you from computing len(s) - 1.
order_id = "O000051"print(order_id[0], order_id[1], order_id[-1], order_id[-2])print(order_id[len(order_id) - 1])O 0 1 51An index past the end raises an IndexError:
store_id = "S01"print(store_id[3])IndexError: string index out of range"S01" has 3 characters, so the valid indexes are 0, 1 and 2 (or −1, −2 and −3).
Slicing: a range of characters
Section titled “Slicing: a range of characters”A slice takes a range of characters and returns a new string. Write s[start:stop]. The slice starts at index start and stops before index stop. The character at stop is not included. This rule (“half-open”) has a useful result: stop - start is the length of the slice.
The timestamps in data/sensors.csv look like 2024-05-01T15:20:00. The date is always the first 10 characters, the hour is at indexes 11 and 12:
timestamp = "2024-05-01T15:20:00"print(timestamp[0:4]) # year: indexes 0, 1, 2, 3print(timestamp[5:7]) # monthprint(timestamp[:10]) # leave out start: from the beginningprint(timestamp[11:]) # leave out stop: to the endprint(timestamp[-8:-3]) # negative indexes work too2024052024-05-0115:20:0015:20A slice has an optional third part, the step: s[start:stop:step] takes every step-th character. A step of -1 walks backwards, so s[::-1] reverses a string.
print("2024-05-01"[::2])print("stressed"[::-1])print(timestamp[100:200] == "") # a slice never raises IndexError22-50dessertsTrue| Slice | Means | "O000051" gives |
|---|---|---|
s[1:] |
all but the first character | '000051' |
s[:-1] |
all but the last character | 'O00005' |
s[:3] |
the first 3 characters | 'O00' |
s[-3:] |
the last 3 characters | '051' |
s[:] |
the whole string | 'O000051' |
s[::-1] |
reversed | '150000O' |
Strings are immutable
Section titled “Strings are immutable”Immutable means “cannot be changed after it is created”. You cannot replace one character of a string:
product_id = "p001"product_id[0] = "P"TypeError: 'str' object does not support item assignmentInstead, build a new string and give it a name. Usually you reuse the old name:
product_id = "p001"product_id = "P" + product_id[1:]print(product_id)P001Immutability makes strings safe to share: no part of a program can change a string that another part is using. The price is that every “change” makes a new string. That is the reason for the most common string bug, shown in the next section.
Methods: functions that belong to a value
Section titled “Methods: functions that belong to a value”A method is a function that belongs to a value. You call it with a dot after the value: region.strip(). Strings have 47 public methods. Because strings are immutable, a string method never changes the string. It returns a new one.
region = " north "region.strip() # the result is thrown awayprint(repr(region))region = region.strip() # keep the resultprint(repr(region))' north ''north'The first call computes 'north' and throws it away. Always assign the result. Because each method returns a string, you can call the next method on the result directly. This is method chaining. Python runs the calls from left to right:
raw_region = " NORTH "clean_region = raw_region.strip().lower().capitalize()print(repr(raw_region), "->", repr(clean_region))' NORTH ' -> 'North'Changing case
Section titled “Changing case”| Method | Does | "anna-lena MÜLLER" gives |
|---|---|---|
lower() |
all lowercase | 'anna-lena müller' |
upper() |
all uppercase | 'ANNA-LENA MÜLLER' |
title() |
first letter of each word upper, the rest lower | 'Anna-Lena Müller' |
capitalize() |
first character upper, the rest lower | 'Anna-lena müller' |
swapcase() |
swaps upper and lower | 'ANNA-LENA müller' |
casefold() |
like lower(), but stronger, for comparisons |
'anna-lena müller' |
title() starts a new word after any character that is not a letter: a space, a hyphen, a digit or an apostrophe. That is right for Anna-Lena and O'Brien, and wrong for other text:
print("o'brien".title(), "jean-luc picard".title())print("chef's knife set".title())print("55-inch 4k smart tv".title())O'Brien Jean-Luc PicardChef'S Knife Set55-Inch 4K Smart TvChef'S and Smart Tv are wrong. Use title() for people’s names and plain labels such as regions. For product names, match against the official list instead (see Example 7).
Case folding turns text into a form for case-insensitive comparison. casefold() is lower() plus extra rules for some languages. The German ß becomes ss:
print("STRASSE".lower() == "straße".lower())print("STRASSE".casefold() == "straße".casefold())FalseTrueUse casefold() when you compare text typed by people. Use lower() when you need text to display.
Removing whitespace and unwanted characters
Section titled “Removing whitespace and unwanted characters”Whitespace is the group of characters that show as empty space: the space, the tab \t, the newline \n and a few rarer ones. Raw data is full of stray whitespace.
| Method | Removes | " S01 \n" gives |
|---|---|---|
strip() |
whitespace at both ends | 'S01' |
lstrip() |
whitespace at the left end | 'S01 \n' |
rstrip() |
whitespace at the right end | ' S01' |
strip("$ ") |
any of the given characters at both ends | — |
removeprefix("$") |
that exact text at the start, once | — |
removesuffix(".csv") |
that exact text at the end, once | — |
print(repr(" North ".strip()))print(repr("$1,299.00".strip("$")))print(repr("**Sale**".strip("*")))print("sales_2024.csv".removesuffix(".csv"))print("sales_2024.csv".strip(".csv")) # a set of characters, not a word!'North''1,299.00''Sale'sales_2024ales_2024The last line is a classic bug. strip(".csv") removes every ., c, s and v at both ends, in any order, so it also eats the s of sales. To remove a known prefix or suffix, use removeprefix() or removesuffix().
strip() never touches the inside of a string. To collapse runs of inner spaces such as "maría josé fernández", split the text into words and join them with one space: " ".join(text.split()). The next sections explain both methods.
Searching inside a string
Section titled “Searching inside a string”| Method | Returns | s = "Running Socks 3-Pack" |
|---|---|---|
"Socks" in s |
True or False |
True |
s.startswith("Run") |
True or False |
True |
s.endswith(("Pack", "Set")) |
True if it ends with any of them |
True |
s.find("Socks") |
index of the first match, or -1 |
8 |
s.find("Shoes") |
-1 when there is no match |
-1 |
s.index("Shoes") |
like find(), but raises ValueError |
ValueError |
s.count("n") |
number of matches (no overlaps) | 3 |
s.rfind("n") |
index of the last match | 5 |
log_line = "2024-05-01 08:08:39,278 INFO [api] 172.16.4.9 POST /api/v1/predict 201"start = log_line.find("[") + 1end = log_line.find("]")print(log_line[start:end])print(log_line.startswith("2024-05"), log_line.count(" "))apiTrue 7find() gives you positions, and a slice cuts between them. This pair extracts the component name api from a line of data/logs/app.log. Module 09 teaches regular expressions for harder patterns.
Replacing and translating characters
Section titled “Replacing and translating characters”replace(old, new) returns a copy with every old replaced by new. An optional third argument limits the number of replacements.
price_text = "$1,299.00"price = float(price_text.removeprefix("$").replace(",", ""))print(price, type(price))print("2023/01/04".replace("/", "-"))print("a-b-c".replace("-", "+", 1))1299.0 <class 'float'>2023-01-04a+b-cTo replace many single characters in one pass, build a translation table with str.maketrans() and apply it with translate(). With two strings, each character of the first maps to the character at the same position in the second. A third string lists characters to delete.
swap = str.maketrans(",.", ".,")print("1,299.00".translate(swap)) # European style: 1.299,00no_punct = str.maketrans("", "", "!?.,")print("Love it!!! Great value, really.".translate(no_punct))1.299,00Love it Great value reallyThe first table swaps commas and dots, which turns a US number into the style used in Germany or Brazil. A plain replace() cannot do this: after the first replacement, you no longer know which dots were commas.
Testing what a string contains
Section titled “Testing what a string contains”These methods return True or False. They help you check a value before you convert it.
| Method | True when every character is… (and the string is not empty) |
"2024" |
"21.7" |
"S01" |
"" |
|---|---|---|---|---|---|
isdigit() |
a digit | True |
False |
False |
False |
isalpha() |
a letter | False |
False |
False |
False |
isalnum() |
a letter or a digit | True |
False |
True |
False |
isspace() |
whitespace | False |
False |
False |
False |
isupper() |
uppercase (at least one cased letter) | False |
False |
True |
False |
islower() |
lowercase (at least one cased letter) | False |
False |
False |
False |
print("2024".isdigit(), "21.7".isdigit(), "-3".isdigit())print("Zoë".isalpha(), "O'Brien".isalpha())True False FalseTrue Falseisdigit() is False for "21.7" and "-3", because . and - are not digits. So isdigit() is not a test for “is a number”. Module 06 shows the reliable test: try float() and catch the ValueError.
Splitting and joining
Section titled “Splitting and joining”split() cuts a string at a delimiter (a separator character such as ,, ;, | or a tab) and returns the pieces as a list. A list is an ordered collection of values, written in square brackets. Module 04 covers lists in depth. For now you need three facts: a list prints with brackets, len() counts its items, and you index it like a string.
line = "O000051,2023-01-04,C01656,S10,west,online,P029,Electric Toothbrush"fields = line.split(",")print(fields)print(len(fields), fields[0], fields[-1])['O000051', '2023-01-04', 'C01656', 'S10', 'west', 'online', 'P029', 'Electric Toothbrush']8 O000051 Electric Toothbrushsplit() with no argument splits on any run of whitespace and drops empty pieces at the ends. That is the tool for messy spacing:
messy = " maría josé fernández "print(messy.split(" ")) # one space: empty strings between double spacesprint(messy.split()) # any whitespace: clean words['', '', 'maría', '', 'josé', '', 'fernández', '']['maría', 'josé', 'fernández']join() does the reverse. Call it on the separator and pass the pieces: ", ".join(pieces). Together, split() and join() collapse inner spaces:
words = messy.split()print(" ".join(words))print("-".join(["2024", "05", "01"]))print(" | ".join(fields[:4]))maría josé fernández2024-05-01O000051 | 2023-01-04 | C01656 | S10Four relatives of split() are worth knowing:
| Method | Does | Example | Result |
|---|---|---|---|
split(",", 1) |
at most 1 split | "a,b,c".split(",", 1) |
['a', 'b,c'] |
rsplit(".", 1) |
split from the right | "report.2024.csv".rsplit(".", 1) |
['report.2024', 'csv'] |
partition(" ") |
split once into (before, separator, after) | "S01 Chicago".partition(" ") |
('S01', ' ', 'Chicago') |
splitlines() |
split at line breaks, drop them | "a\nb\n".splitlines() |
['a', 'b'] |
Reading the examples: lists and for loops
Section titled “Reading the examples: lists and for loops”Cleaning one string is a method call. Cleaning 20 names means doing the same thing 20 times. A for loop repeats a block of code once for each item of a list. Module 03 covers loops in full. This is all you need to read the examples:
regions = [" north", "SOUTH ", "East"]for region in regions: print(repr(region), "->", region.strip().title())' north' -> North'SOUTH ' -> South'East' -> EastRead it as “for each region in the list, run the indented line”. The colon ends the for line. The indented lines below it are the loop body. region takes each value in turn. To collect results, start with an empty list [] and add each result with the list method append():
clean = []for region in regions: clean.append(region.strip().title())print(clean)['North', 'South', 'East']Comparing and sorting strings
Section titled “Comparing and sorting strings”== compares strings character by character, and the case matters. < and > compare strings in lexicographic order: the order of a dictionary, but based on each character’s Unicode number (see Characters and Unicode). Digits come first, then the ASCII uppercase letters A-Z, then the ASCII lowercase letters a-z. Accented letters such as É and é come after all of them.
print("North" == "north", "North".casefold() == "north".casefold())print("apple" < "banana", "Zoë" < "anna", "S10" < "S9")print(sorted(["west", "East", "north", "South"]))print(sorted(["west", "East", "north", "South"], key=str.casefold))False TrueTrue True True['East', 'South', 'north', 'west']['East', 'north', 'South', 'west']"Zoë" < "anna" is True because Z comes before a. "S10" < "S9" is True because the second characters compare first, and 1 comes before 9. The built-in function sorted() returns a sorted list. With key=str.casefold, it compares the case-folded forms, which gives the order that people expect. Module 05 explains key=. To make ids sort correctly as text, pad them with zeros: S09 sorts before S10.
f-strings in depth
Section titled “f-strings in depth”Module 01 introduced the f-string: a string literal with f before the quote, in which each part in curly braces is replaced by the value of an expression. A part in curly braces is a replacement field. Any expression works in a replacement field: arithmetic, method calls and indexing.
product = "Noise-Cancelling Headphones"unit_price = 249.0quantity = 3discount = 0.1print(f"{quantity} x {product.upper()} = {quantity * unit_price * (1 - discount)}")print(f"{product[:5]}... costs {unit_price / 100} hundred USD")3 x NOISE-CANCELLING HEADPHONES = 672.3000000000001Noise... costs 2.49 hundred USDA replacement field has three optional parts after the expression, in this order:
{ expression = !r : format_spec } ▲ ▲ ▲ │ │ └── how the value looks: width, decimals, ... │ └── conversion: !r uses repr(), !s uses str() └── self-documenting: show "expression=" before the valueregion = " North "revenue = 888229.47print(f"{region!r}") # shows the spacesprint(f"{revenue=}") # debug: name and valueprint(f"{revenue=:,.2f}") # debug with a format specprint(f"{region=}") # the = form uses repr() by defaultprint(f"Literal braces: {{revenue}} -> {revenue:.0f}")' North 'revenue=888229.47revenue=888,229.47region=' North 'Literal braces: {revenue} -> 888229The = form shows the value with repr() unless you give a format spec, so region=' North ' keeps its quotes and spaces. To show a literal brace in an f-string, double it: {{ or }}. A long f-string can span several lines. Put several f-strings in parentheses, and Python joins them:
summary = ( f"Product: {product}, " f"units: {quantity}, " f"revenue: {quantity * unit_price * (1 - discount):.2f} USD")print(summary)Product: Noise-Cancelling Headphones, units: 3, revenue: 672.30 USDThe format spec mini-language
Section titled “The format spec mini-language”The format spec is the code after the colon. Its small grammar is called the format spec mini-language. Every part is optional, but the parts that you use must come in this order:
[[fill]align][sign][z][#][0][width][grouping][.precision][type]| Part | Values | Meaning | Example | Result |
|---|---|---|---|---|
| fill | any character | the character that pads to the width (needs an align) | f"{7:*>4}" |
'***7' |
| align | < > ^ = |
left, right, center, sign first then padding | f"{'S01':^7}" |
' S01 ' |
| sign | + - |
sign on all numbers, negatives only (default), space for positives | f"{3.5:+}" |
'+3.5' |
z |
z |
show -0.00 as 0.00 |
f"{-0.001:z.2f}" |
'0.00' |
# |
# |
alternate form: 0x before hex, 0b before binary |
f"{255:#x}" |
'0xff' |
0 |
0 |
pad numbers with zeros after the sign | f"{-42:05}" |
'-0042' |
| width | a whole number | the minimum total width in characters | f"{42:6}" |
' 42' |
| grouping | , _ |
thousands separator | f"{1375000:,}" |
'1,375,000' |
| precision | . and a number |
digits after the point (f, e, %), significant digits (g), or the maximum length of a string |
f"{79.99:.1f}" |
'80.0' |
| type | d f e g % s x b … |
how to present the value | f"{0.1926:.1%}" |
'19.3%' |
The field width is the minimum number of characters a value takes. Shorter values are padded: filled up with the fill character (a space unless you choose another). The alignment decides where the padding goes. By default, numbers align right and text aligns left, which is what a table needs.
print(f"[{'S01':8}] [{42:8}]") # defaults: text left, numbers rightprint(f"[{'S01':<8}] [{'S01':>8}] [{'S01':^8}]")print(f"[{'S01':.<8}] [{42:0>8}] [{-42:=8}]")print(f"[{'Noise-Cancelling Headphones':.12}]") # precision cuts textprint(f"[{'Noise-Cancelling Headphones':5}]") # width never cuts[S01 ] [ 42][S01 ] [ S01] [ S01 ][S01.....] [00000042] [- 42][Noise-Cancel][Noise-Cancelling Headphones]The width is a minimum, never a maximum. A long value pushes the rest of the line to the right. To cut text to a fixed length, give a precision: :.12 keeps at most 12 characters.
Formatting numbers for reports
Section titled “Formatting numbers for reports”The presentation type is the letter at the end of a spec. It decides how a number is written:
| Type | Name | 1234.5678 |
0.0456 |
Use |
|---|---|---|---|---|
| none | general | 1234.5678 |
0.0456 |
the default str() look |
d |
decimal integer | (ints only) | (ints only) | counts, ids |
f |
fixed point | 1234.567800 |
0.045600 |
money, measurements (6 decimals unless you give a precision) |
e |
scientific | 1.234568e+03 |
4.560000e-02 |
very large or very small values |
g |
general | 1234.57 |
0.0456 |
the shortest sensible form (.6 significant digits by default) |
% |
percentage | 123456.780000% |
4.560000% |
rates; multiplies by 100 |
x, b, o |
hex, binary, octal | (ints only) | (ints only) | colors, bit flags, file permissions |
Precision is the number after the dot. With f, e and %, it is the number of digits after the decimal point. With g, it counts significant digits. So f"{1234.5678:.2e}" and f"{1234.5678:.3g}" both give '1.23e+03': 2 digits after the point, or 3 significant digits. A thousands separator (, or _) groups the digits of large numbers in threes.
This block formats the sales headline numbers from data/sales.csv:
revenue_2023 = 1645589.59revenue_2024 = 1950934.24units = 29533 # both yearsonline_share = 0.4199624 # share of order lines that were online, both yearsgrowth = revenue_2024 / revenue_2023 - 1
print(f"Revenue 2024: {revenue_2024:,.2f} USD") # moneyprint(f"Revenue 2024: {revenue_2024 / 1e6:.2f}M USD") # in millionsprint(f"Units 2023-2024: {units:,d}") # countprint(f"Units 2023-2024: {units:_d}") # underscores, as in Python literalsprint(f"Growth 2024: {growth:+.1%}") # signed percentageprint(f"Online 2023-2024: {online_share:.0%}") # share of order lines, whole %print(f"Tiny p-value: {0.0000123:.2e}") # scientific: 2 digits after the pointprint(f"Rating: {3.8423:.3g}") # 3 significant digitsRevenue 2024: 1,950,934.24 USDRevenue 2024: 1.95M USDUnits 2023-2024: 29,533Units 2023-2024: 29_533Growth 2024: +18.6%Online 2023-2024: 42%Tiny p-value: 1.23e-05Rating: 3.84Four rules of number formatting:
- A format spec changes only how a value looks. The variable keeps its full value.
%multiplies by 100 for you. Store rates as fractions (0.186), never as18.6.- Formatting rounds the exact binary value that the float stores to the requested number of decimal digits. Exact ties go to the even digit.
f"{0.125:.2f}"is'0.12'.f"{2.675:.2f}"is'2.67'too, because the float 2.675 is really 2.67499999… (module 01, float precision). - A tiny negative value can show as
-0.00. Addzto show0.00:f"{-0.004:z.2f}".
>>> f"{0.125:.2f} {0.375:.2f} {2.675:.2f}"'0.12 0.38 2.67'>>> f"{-0.004:.2f} {-0.004:z.2f}"'-0.00 0.00'>>> f"{7:03d} {-3.5:08.2f} {1234567:,} {1234567.891:_.1f}"'007 -0003.50 1,234,567 1_234_567.9'You can combine a fill, an alignment, a width, a grouping and a precision in one spec. A spec can even contain replacement fields of its own, so the width can come from a variable. This is a nested format spec:
width = 16decimals = 1print(f"[{revenue_2024:>{width},.{decimals}f}]")print(f"[{revenue_2024:*^{width},.0f}]")[ 1,950,934.2][***1,950,934****]Aligned text tables
Section titled “Aligned text tables”A text table is a report in plain text with columns that line up. It works in a terminal, a log file, an email and a code review. The recipe:
- Choose a width for each column. Make it at least as wide as the longest value and the header.
- Align text left (
<) and numbers right (>), so that the decimal points line up. - Format the header with the same widths and alignments as the rows.
- Draw separator lines with
"-" * total_width.
print(f"{'Region':<8}{'Revenue (USD)':>16}{'Share':>8}")print("-" * 32)print(f"{'East':<8}{993683.72:>16,.2f}{0.2763:>8.1%}")print(f"{'South':<8}{891766.07:>16,.2f}{0.2480:>8.1%}")print("-" * 32)Region Revenue (USD) Share--------------------------------East 993,683.72 27.6%South 891,766.07 24.8%--------------------------------Each column’s spec in the header has the same width as in the rows: 8, 16 and 8 characters, 32 in total. Example 4 builds the full table with a loop and a total row.
Strings also have padding methods, which are useful when the width is in a variable: ljust(width), rjust(width), center(width, fill) and zfill(width) (pad with zeros).
print("[" + "East".ljust(8) + "]", "[" + "East".rjust(8) + "]")print(" Sales report ".center(32, "="))print("51".zfill(6), "-7".zfill(4))[East ] [ East]========= Sales report =========000051 -007str.format() and % formatting
Section titled “str.format() and % formatting”f-strings arrived in Python 3.6. You will still read two older styles in tutorials, libraries and old scripts. str.format() and the built-in format() use the same format specs as f-strings. % formatting uses an older printf-style syntax that looks similar but has fewer options: no , separator, no ^ centering and no nested fields.
row = "{:<8}{:>16,.2f}" # a template with two empty replacement fieldsprint(row.format("North", 888229.47))print("{region}: {revenue:,.0f}".format(region="West", revenue=822844.57))print("%s: %.2f" % ("South", 891766.07)) # the oldest style, printf-likeprint(format(1950934.24, ",.2f")) # the built-in format() applies one specNorth 888,229.47West: 822,845South: 891766.071,950,934.24str.format() is the right tool when the template must exist before the values do: a row layout that you define once and fill many times, or a template stored in a config file. For everything else, use f-strings. They are shorter and faster.
Characters, code points and Unicode
Section titled “Characters, code points and Unicode”A computer stores numbers, not letters. Unicode is the world standard that gives every character a number, from A to é, ł, €, Ğ and emoji. That number is the character’s code point. Python’s str is a sequence of Unicode code points, so one string can mix every language.
The built-in function ord() gives the code point of a character. chr() does the reverse. Code points are often written in hexadecimal (base 16) as U+00E9.
print(ord("A"), ord("a"), ord("é"), ord("€"))print(chr(233), "\u00e9", f"U+{ord('é'):04X}")print(len("Zoë"), len("NGUYỄN"))65 97 233 8364é é U+00E93 6This explains the sort order of the previous section: ord("Z") is 90 and ord("a") is 97, so "Zoë" < "anna".
Bytes and encodings
Section titled “Bytes and encodings”Files and networks do not store code points. They store bytes. A byte is a number from 0 to 255 (8 bits). A character encoding is a rule that turns code points into bytes and back:
- To encode is to turn a
strintobytes:text.encode("utf-8"). - To decode is to turn
bytesinto astr:data.decode("utf-8").
flowchart LR
S["str: 'Köln'<br/>4 code points"] -- "encode('utf-8')" --> B["bytes: b'K\xc3\xb6ln'<br/>5 bytes"]
B -- "decode('utf-8')" --> S
F["file, network,<br/>database"] <--> B
Python has a separate type for raw data, bytes. A bytes literal has a b before the quote. Python shows each byte that is not a plain ASCII character as \x and two hexadecimal digits.
city = "Köln"utf8 = city.encode("utf-8") # UTF-8 is also the defaultlatin1 = city.encode("latin-1")print(utf8, len(utf8), type(utf8))print(latin1, len(latin1))print(utf8.decode("utf-8"), latin1.decode("latin-1"))print(list(utf8)) # a bytes object is a sequence of numbers 0-255b'K\xc3\xb6ln' 5 <class 'bytes'>b'K\xf6ln' 4Köln Köln[75, 195, 182, 108, 110]Three encodings cover almost all data work:
| Encoding | Bytes per character | Characters | Where you meet it |
|---|---|---|---|
| ASCII | 1 | 128: English letters, digits, punctuation | old protocols; a subset of the other two |
| UTF-8 | 1 to 4 | all of Unicode | the default on the web, in Python source files, JSON and modern CSV files |
| latin-1 (ISO-8859-1) | 1 | 256: ASCII plus Western European letters such as é, ü, ñ |
old databases, legacy exports, some Excel files |
UTF-8 writes ASCII characters as 1 byte and others as 2 to 4 bytes. That is why "Köln" has 4 characters but 5 UTF-8 bytes. latin-1 uses exactly 1 byte per character, but it cannot store ł, Ğ, € or any Asian script. Windows uses a close relative of latin-1, cp1252, which adds € and curly quotes.
Decoding errors and mojibake
Section titled “Decoding errors and mojibake”Decoding with the wrong encoding fails in one of two ways.
A loud failure. Not every series of bytes is valid UTF-8. When Python meets an invalid one, it raises a UnicodeDecodeError. The message names the codec, the bad byte and its position:
supplier = "Café Müller".encode("latin-1")print(supplier)print(supplier.decode("utf-8"))b'Caf\xe9 M\xfcller'UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 3: invalid continuation byteIn latin-1, é is the single byte 0xe9. In UTF-8, a byte such as 0xe9 must start a multi-byte character, and the next byte (a space) does not continue it. So the decoder stops.
A silent failure. Every byte is a valid latin-1 character, so decoding as latin-1 never fails, even when it is wrong. UTF-8 bytes decoded as latin-1 give mojibake: garbled text such as Café. You see it on web pages and in exports when one program writes UTF-8 and another reads latin-1.
utf8_bytes = "Café Müller".encode("utf-8")garbled = utf8_bytes.decode("latin-1")print(garbled)print(garbled.encode("latin-1").decode("utf-8")) # undo the wrong stepCafé MüllerCafé MüllerTo repair mojibake, reverse the mistake: encode with the wrong encoding to get the original bytes back, then decode with the right one.
The errors= argument chooses what happens to bad bytes. The default "strict" raises. "replace" puts the replacement character � (U+FFFD) in place of each bad byte when you decode. When you encode, "replace" writes ? for each character that the encoding cannot store. Use it to look at a broken file, never to hide the problem in a pipeline:
print(supplier.decode("utf-8", errors="replace"))print("Łukasz".encode("ascii", errors="replace"))Caf� M�llerb'?ukasz'| Symptom | Cause | Fix |
|---|---|---|
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 |
the bytes are latin-1 or cp1252 | decode with "latin-1" or "cp1252" |
Café, Müller, ’ |
UTF-8 bytes were decoded as latin-1 or cp1252 | text.encode("cp1252").decode("utf-8") |
� in the text |
bytes were decoded with errors="replace" |
find the right encoding; the original bytes are lost |
\ufeff at the start of the first column name |
a UTF-8 file with a BOM (Excel’s “CSV UTF-8”) | decode with "utf-8-sig" |
For the mojibake repair, encode with "cp1252" when the garbled text contains €, ™ or curly quotes (’): latin-1 cannot store these characters and raises a UnicodeEncodeError. Otherwise, "latin-1" and "cp1252" give the same result.
A BOM (byte order mark) is the invisible character U+FEFF at the very start of a file. Some Windows programs write it to mark a file as UTF-8. The encoding "utf-8-sig" removes it.
Unicode normalization and accents
Section titled “Unicode normalization and accents”Unicode can store some characters in two ways. é can be one code point (U+00E9, “e with acute”), or two: a plain e followed by a combining character (U+0301, “combining acute accent”), a code point that adds a mark to the character before it. Both look identical on screen, but they are different strings:
import unicodedata
composed = "Jos\u00e9" # é as one code pointdecomposed = "Jose\u0301" # e + combining accentprint(composed, decomposed, composed == decomposed)print(len(composed), len(decomposed))print(unicodedata.name(decomposed[-1]))José José False4 5COMBINING ACUTE ACCENTUnicode normalization converts text to one standard form, so that equal-looking strings become equal. The unicodedata module of the standard library does it:
- NFC (normalization form C, “composed”) uses one code point per accented letter where one exists. Use NFC for storage and comparison.
- NFD (“decomposed”) splits each accented letter into the base letter and combining marks.
- NFKC and NFKD also replace “compatibility” characters with plain ones: the ligature
fibecomesfiand the superscript²becomes2.
print(unicodedata.normalize("NFC", decomposed) == composed)print(len(unicodedata.normalize("NFD", "Zoë García")))print(unicodedata.normalize("NFKC", "file size: 12 m²"))True12file size: 12 m2Some macOS file names, text copied from PDFs and some web forms arrive in NFD form. Normalize to NFC as soon as text enters your program.
Sometimes you want text without accents, for example a search key so that Malmo finds Malmö. Decompose with NFKD, then encode to ASCII and drop what does not fit with errors="ignore". The combining marks are not ASCII, so they disappear:
names = "Dvořák, Malmö, São Paulo, Søren, Łukasz"decomposed_names = unicodedata.normalize("NFKD", names)ascii_key = decomposed_names.encode("ascii", "ignore").decode("ascii")print(ascii_key)Dvorak, Malmo, Sao Paulo, Sren, ukaszLook at Sren and ukasz. The letters ø and ł are separate letters, not o and l with an accent, so NFKD cannot split them and the ASCII step deletes them. Keep accent-free text for search and matching keys only. Always store and display the real name.
A cleaning recipe for messy text
Section titled “A cleaning recipe for messy text”Messy text has the same problems again and again. Apply the fixes in a fixed order, so that each step can rely on the previous one:
flowchart LR
A["raw text"] --> B["decode with<br/>the right encoding"]
B --> C["normalize<br/>to NFC"]
C --> D["strip ends and<br/>collapse spaces"]
D --> E["fix the case"]
E --> F["map variants<br/>to one value"]
F --> G["clean text"]
| Problem | Example | Fix |
|---|---|---|
| wrong encoding | UnicodeDecodeError, Café |
decode with the right encoding |
| decomposed accents | José that is not == "José" |
unicodedata.normalize("NFC", s) |
| spaces at the ends | " North " |
s.strip() |
| repeated inner spaces | "maría josé" |
" ".join(s.split()) |
| inconsistent case | "NORTH", "north" |
s.title() for names and labels; s.casefold() for comparison keys |
| missing-value tokens | "", "N/A", "-" |
treat them as missing (None), not as a category |
| variant spellings | "55-inch 4k smart tv" |
match a case-folded key against the official list |
The value you map variants to is the canonical form: the one agreed spelling of a value, such as North for north, NORTH and North. Pick it once, write it down and map every variant to it. Module 26 does the same cleaning on whole columns with pandas.
Worked examples
Section titled “Worked examples”Example 1 — Take apart ids and timestamps
Section titled “Example 1 — Take apart ids and timestamps”Goal: Extract the date and time parts of a sensor timestamp from data/sensors.csv, read the number inside an order id, and generate the next order id in the same format.
Step 1 — Slice the timestamp
Section titled “Step 1 — Slice the timestamp”timestamp = "2024-05-09T15:20:00"date_part = timestamp[:10]time_part = timestamp[11:16]print(date_part, time_part)print(timestamp[10] == "T")2024-05-09 15:20TrueISO timestamps have fixed positions: the date fills indexes 0 to 9, the T is index 10, and HH:MM fills 11 to 15. The slice [11:16] stops before index 16, so it gives exactly 5 characters.
Step 2 — Convert the parts to numbers
Section titled “Step 2 — Convert the parts to numbers”year = int(timestamp[:4])month = int(timestamp[5:7])day = int(timestamp[8:10])hour = int(timestamp[11:13])print(year, month, day, hour, type(day))2024 5 9 15 <class 'int'>int("09") is 9: leading zeros are fine in text. Each slice is a new string, so timestamp itself never changes.
Step 3 — Read the number inside an order id
Section titled “Step 3 — Read the number inside an order id”order_id = "O014877"prefix = order_id[0]number = int(order_id[1:])print(prefix, number, len(order_id))O 14877 7order_id[1:] drops the letter. int() drops the leading zero. The number tells you that this is the 14,877th order.
Step 4 — Build the next id with zero padding
Section titled “Step 4 — Build the next id with zero padding”next_id = f"{prefix}{number + 1:06d}"print(next_id, len(next_id) == len(order_id))print(f"O{1:06d}", f"O{51:06d}")O014878 TrueO000001 O000051The spec :06d writes a whole number with at least 6 digits and fills the left with zeros. The new id has the same length as the old ones, so ids still sort in the right order as text.
Common mistakes:
- Writing
timestamp[11:13]astimestamp[11:12]. The stop index is excluded, so that slice has only one digit. Check withstop - start= the length you want. - Using
str(number + 1)to build the id. Without padding, ids get different lengths, and text order breaks:"O9" > "O10"isTrue. Always pad ids to a fixed width. - Slicing a timestamp that is not in ISO format.
07/01/2023puts the day first. Check the format before you slice (timestamp[4] == "-").
Example 2 — Parse and clean one raw sales line
Section titled “Example 2 — Parse and clean one raw sales line”Goal: Line 5 of data/sales_raw.csv has a lowercase region, a price with a dollar sign and an empty discount. Clean each field, compute the revenue and check it against the file.
Step 1 — Split the line into fields
Section titled “Step 1 — Split the line into fields”raw = ( "O000051,2023-01-04,C01656,S10,west,online," "P029,Electric Toothbrush,Beauty,$59.99,4,,239.96")fields = raw.split(",")print(len(fields))print(fields[4], fields[9], repr(fields[11]), fields[12])13west $59.99 '' 239.96The file has 13 columns, so this line splits into 13 fields. Two commas in a row (4,,239.96) give an empty string for the discount.
Step 2 — Clean the text fields
Section titled “Step 2 — Clean the text fields”order_id = fields[0]region = fields[4].strip().title()product = " ".join(fields[7].split())print(order_id, region, product)O000051 West Electric Toothbrushstrip().title() turns west, WEST and West into West. " ".join(s.split()) removes stray spaces at the ends and in the middle of the product name. Run these cleaners on every field, even when this line looks clean: the next line may not be.
Step 3 — Convert the numbers
Section titled “Step 3 — Convert the numbers”unit_price = float(fields[9].removeprefix("$").replace(",", ""))quantity = int(fields[10])discount_text = fields[11].strip()discount = float(discount_text or "0")print(unit_price, quantity, discount)59.99 4 0.0removeprefix("$") drops the dollar sign and replace(",", "") drops any thousands separator. The empty discount is falsy (module 01), so discount_text or "0" gives "0". Here an empty discount means “no discount”; check this with the data owner before you assume it in real work.
Step 4 — Compute the revenue and check it
Section titled “Step 4 — Compute the revenue and check it”import math
revenue = round(unit_price * quantity * (1 - discount), 2)file_revenue = float(fields[12])print(f"{order_id} | {region} | {product} | {quantity} x {unit_price} = {revenue}")print(math.isclose(revenue, file_revenue, abs_tol=0.01))O000051 | West | Electric Toothbrush | 4 x 59.99 = 239.96TrueThe recomputed revenue matches the value in the file. Module 01 taught you not to compare floats with ==. Use math.isclose(), here with an absolute tolerance of 0.01 USD, because the file’s rounding can differ from Python’s round() by one cent on some rows. A check like this tells you that you read every column correctly.
Common mistakes:
- Calling
fields[4].strip()without assigning the result. The field stays dirty. - Calling
float("$59.99"). It raisesValueError: could not convert string to float: '$59.99'. Remove the$first. - Using
strip("$")on"$1,299.00"and forgetting the comma.float("1,299.00")raises aValueError. Remove the separator withreplace(",", "").
Example 3 — Format a KPI summary for a report
Section titled “Example 3 — Format a KPI summary for a report”Goal: Turn the sales headline numbers into a short, readable summary for a management e-mail. A KPI (key performance indicator) is one number that a business tracks to judge performance, such as revenue or growth.
Step 1 — Look at the raw values
Section titled “Step 1 — Look at the raw values”revenue_2023 = 1645589.59revenue_2024 = 1950934.24lines_2024 = 11147online_share_2024 = 0.4620growth = revenue_2024 / revenue_2023 - 1print(revenue_2024, growth, online_share_2024)1950934.24 0.18555334322453998 0.462Raw floats are hard to read: no thousands separators, too many decimals and a rate instead of a percentage.
Step 2 — Choose a spec for each number
Section titled “Step 2 — Choose a spec for each number”print(f"{revenue_2024:,.2f}")print(f"{growth:+.1%}")print(f"{online_share_2024:.1%}")print(f"{lines_2024:,}")print(f"{revenue_2024 / lines_2024:,.2f}")1,950,934.24+18.6%46.2%11,147175.02Money gets , and 2 decimals. Growth gets a sign, because the reader must see at once if it went up or down. A share gets % with 1 decimal. A count gets only the separator.
Step 3 — Build aligned label–value lines
Section titled “Step 3 — Build aligned label–value lines”label_width = 22print(f"{'Revenue 2024 (USD)':<{label_width}}{revenue_2024:>14,.2f}")print(f"{'Growth vs 2023':<{label_width}}{growth:>14.1%}")print(f"{'Online share of lines':<{label_width}}{online_share_2024:>14.1%}")print(f"{'Order lines':<{label_width}}{lines_2024:>14,}")Revenue 2024 (USD) 1,950,934.24Growth vs 2023 18.6%Online share of lines 46.2%Order lines 11,147Every label has the same width (22) and every value the same width (14), so the numbers line up on the right edge. The width of the labels is a variable: change it once and every line follows.
Step 4 — Add a title bar
Section titled “Step 4 — Add a title bar”total_width = label_width + 14print(f"{' KPI summary 2024 ':=^{total_width}}")print(f"{'Revenue 2024 (USD)':<{label_width}}{revenue_2024:>14,.2f}")print(f"{'Growth vs 2023':<{label_width}}{growth:>+14.1%}")print("=" * total_width)========= KPI summary 2024 =========Revenue 2024 (USD) 1,950,934.24Growth vs 2023 +18.6%=====================================^36 centers the title in 36 characters and fills both sides with =. In >+14.1%, the parts come in grammar order: align, sign, width, precision, type.
Common mistakes:
- Writing the growth as
growth * 100with%. The%type already multiplies by 100, so you get1855.5%. - Writing
:+>14.1%. The sign must come after the alignment::>+14.1%. In the wrong order,+becomes the fill character:+++++++++18.6%. - Rounding the values with
round()before you compute the growth. Round only when you display.
Example 4 — Print an aligned table of revenue by category
Section titled “Example 4 — Print an aligned table of revenue by category”Goal: Print the revenue of each product category in data/sales.csv as an aligned text table with units, revenue, share of total and a total row.
Step 1 — Store the figures as text
Section titled “Step 1 — Store the figures as text”category_csv = """category,units,revenueElectronics,4462,1808108.17Home,4054,672294.61Sports,4547,544108.55Clothing,6522,314686.62Beauty,5491,150417.76Books,4457,106908.12"""rows = category_csv.splitlines()[1:] # drop the header lineprint(len(rows), rows[0])6 Electronics,4462,1808108.17The figures were summed from data/sales.csv (module 25 shows how with pandas). Here they are a small CSV text in a triple-quoted string. splitlines() gives one string per line, and [1:] drops the header.
Step 2 — Compute the total
Section titled “Step 2 — Compute the total”total_revenue = 0.0total_units = 0for row in rows: parts = row.split(",") total_units += int(parts[1]) total_revenue += float(parts[2])print(total_units, round(total_revenue, 2))29533 3596523.83The loop splits each line and adds the units and the revenue to two running totals. The share of each category needs the total, so the total comes first.
Step 3 — Print the header and the rows
Section titled “Step 3 — Print the header and the rows”header = f"{'Category':<12}{'Units':>8}{'Revenue (USD)':>16}{'Share':>8}"print(header)print("-" * len(header))for row in rows: parts = row.split(",") revenue = float(parts[2]) share = revenue / total_revenue print(f"{parts[0]:<12}{int(parts[1]):>8,}{revenue:>16,.2f}{share:>8.1%}")Category Units Revenue (USD) Share--------------------------------------------Electronics 4,462 1,808,108.17 50.3%Home 4,054 672,294.61 18.7%Sports 4,547 544,108.55 15.1%Clothing 6,522 314,686.62 8.7%Beauty 5,491 150,417.76 4.2%Books 4,457 106,908.12 3.0%Each column has the same width in the header and in the rows: 12, 8, 16 and 8. The category name is left-aligned, every number right-aligned, so units, decimal points and percent signs line up. "-" * len(header) makes the separator as wide as the header.
Step 4 — Add the total row
Section titled “Step 4 — Add the total row”print("-" * len(header))print(f"{'Total':<12}{total_units:>8,}{total_revenue:>16,.2f}{1:>8.1%}")--------------------------------------------Total 29,533 3,596,523.83 100.0%The total row uses the same specs, so it lines up with the rows above. Its share is 1, shown as 100.0%. The total revenue, 3,596,523.83 USD, equals the total of data/sales.csv.
Common mistakes:
- Giving the header different widths from the rows. The columns drift apart. Build the header and the rows with the same widths, or store each width in a variable.
- Forgetting the
>for a text header above a number column. Text aligns left by default, soUnitswould sit to the left of its numbers. - Choosing widths that are too small. A width is a minimum:
1,808,108.17is 12 characters and pushes the line right when the column is only 10 wide.
Example 5 — Read a legacy latin-1 file
Section titled “Example 5 — Read a legacy latin-1 file”Goal: A supplier list arrives from an old system as data/legacy_latin1.csv. Read it, find out why UTF-8 fails, decode it correctly and save a UTF-8 copy.
Step 1 — Read the raw bytes
Section titled “Step 1 — Read the raw bytes”from pathlib import Path
raw_bytes = Path("data/legacy_latin1.csv").read_bytes()print(type(raw_bytes), len(raw_bytes))print(raw_bytes[:60])<class 'bytes'> 562b'supplier_id,supplier,city,country,since\nSUP01,Caf\xe9 M\xfcller Gm'Path from the pathlib module represents a file path. Its method read_bytes() returns the file content as bytes, with no decoding. Module 07 covers pathlib in full. The bytes show \xe9 where you expect é and \xfc where you expect ü: one byte per accented letter. That is a strong sign of latin-1.
Step 2 — Try to decode as UTF-8
Section titled “Step 2 — Try to decode as UTF-8”text = raw_bytes.decode("utf-8")UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 49: invalid continuation byteThe byte at position 49 is 0xe9, the é of Café. It is not valid UTF-8 there, so the decoder raises a UnicodeDecodeError. Path.read_text(encoding="utf-8") fails in the same way.
Step 3 — Decode as latin-1
Section titled “Step 3 — Decode as latin-1”text = raw_bytes.decode("latin-1")lines = text.splitlines()print(len(lines))print(lines[0])print(lines[1])print(lines[12])13supplier_id,supplier,city,country,sinceSUP01,Café Müller GmbH,Köln,Germany,2015SUP12,Ñandú Outdoor,Asunción,Paraguay,2023With the right encoding, every name is readable. The file has a header and 12 supplier rows. Path("data/legacy_latin1.csv").read_text(encoding="latin-1") reads and decodes in one step.
Step 4 — Save a UTF-8 copy and compare the sizes
Section titled “Step 4 — Save a UTF-8 copy and compare the sizes”out_dir = Path("output")out_dir.mkdir(exist_ok=True)out_file = out_dir / "suppliers_utf8.csv"out_file.write_text(text, encoding="utf-8")utf8_bytes = out_file.read_bytes()print(len(raw_bytes), len(utf8_bytes), len(utf8_bytes) - len(raw_bytes))print(out_file.read_text(encoding="utf-8") == text)562 591 29Truewrite_text() encodes the string with the encoding you name. The UTF-8 copy is 29 bytes larger: each of the 29 accented letters takes 2 bytes instead of 1. The text is identical, so nothing was lost. Other tools (pandas, databases, web pages) now read the file without an encoding= argument.
Common mistakes:
- Decoding with
errors="ignore"to make the error go away. The accented letters vanish:Caf Mller GmbH. Find the right encoding instead. - Guessing latin-1 for every file that fails. latin-1 never raises, so a wrong guess gives mojibake silently. Check a few known names (
Café Müller) after you decode. - Writing the copy without
encoding="utf-8". On a machine with another default encoding, the file is not UTF-8.
Example 6 — Clean a list of messy names
Section titled “Example 6 — Clean a list of messy names”Goal: data/messy_names.txt holds 20 customer names typed by hand in a CRM (customer relationship management) system, with odd spacing, odd case and two kinds of accents. Clean them into one consistent form and find the duplicates.
Step 1 — Read the file and look at the raw lines
Section titled “Step 1 — Read the file and look at the raw lines”names_text = Path("data/messy_names.txt").read_text(encoding="utf-8")raw_names = names_text.splitlines()print(len(raw_names))print(repr(raw_names[0]))print(repr(raw_names[7]))print(repr(raw_names[18]))20' josé GARCÍA ''José García'"o'neill, PATRICK"repr() shows the extra spaces of line 1. Line 8 looks clean. Line 19 has the last name first, separated by a comma.
Step 2 — Find the hidden difference
Section titled “Step 2 — Find the hidden difference”first = " ".join(raw_names[0].split()).title()eighth = raw_names[7]print(first, eighth, first == eighth)print(len(first), len(eighth))print(len(unicodedata.normalize("NFC", eighth)))José García José García False11 1311After stripping and title case, line 1 reads José García, exactly like line 8. Yet == is False, and line 8 is 2 characters longer. Line 8 is in NFD form: its é and í are each a base letter plus a combining accent. NFC normalization joins them, and the length drops to 11.
Step 3 — Clean every name in a fixed order
Section titled “Step 3 — Clean every name in a fixed order”clean_names = []for raw_name in raw_names: name = unicodedata.normalize("NFC", raw_name) name = " ".join(name.split()) name = " ".join(reversed(name.split(", "))) # "last, first" -> "first last" name = name.title() clean_names.append(name)print(clean_names[0], "|", clean_names[7], "|", clean_names[18])print(clean_names[0] == clean_names[7])José García | José García | Patrick O'NeillTrueThe loop applies the recipe to each line: normalize, collapse spaces, fix the name order, fix the case. split(", ") gives ["o'neill", 'PATRICK'] for line 19 and a single piece for the other names. The built-in function reversed() flips the pieces, and " ".join() puts them back together. A name without a comma passes through unchanged.
Step 4 — Print the clean list and count the duplicates
Section titled “Step 4 — Print the clean list and count the duplicates”print(" | ".join(clean_names[0:5]))print(" | ".join(clean_names[5:10]))print(" | ".join(clean_names[10:15]))print(" | ".join(clean_names[15:20]))print(len(clean_names), "names,", len(set(clean_names)), "distinct")José García | Zoë O'Brien | François Dupont | Björk Guðmundsdóttir | Anna-Lena MüllerSøren Kierkegaard | Mei Chen | José García | Renée O'Connor | Çağla YılmazŁukasz Nowak | María José Fernández | Zoë O'Brien | Jean-Luc Picard | Émile ZolaNguyễn Văn An | Aoife Ní Bhriain | Ana Silva | Patrick O'Neill | Dvořák Antonín20 names, 18 distinctEvery name now has single spaces, title case and NFC accents. set() keeps one copy of each distinct value (module 04 covers sets), so 18 distinct names means 2 duplicates: lines 1 and 8, and lines 2 and 13. Before cleaning, all 20 lines were different.
Step 5 — Build accent-free search keys
Section titled “Step 5 — Build accent-free search keys”for name in clean_names[:4]: key = unicodedata.normalize("NFKD", name).encode("ascii", "ignore").decode() print(f"{name:<24} -> {key.casefold()}")José García -> jose garciaZoë O'Brien -> zoe o'brienFrançois Dupont -> francois dupontBjörk Guðmundsdóttir -> bjork gumundsdottirA search box can compare a user’s typing with these keys, so jose garcia finds José García. The keys are only for matching. Björk Guðmundsdóttir loses its ð and becomes gumundsdottir, which is not a real spelling.
Common mistakes:
- Comparing names before NFC normalization. Equal-looking names stay different, and duplicates survive.
- Collapsing spaces with
split(" "). Double spaces give empty strings, and" ".join()puts the double spaces back. Usesplit()with no argument. - Storing the accent-free key instead of the name. You lose information you cannot get back.
Example 7 — Clean product and region labels in raw sales data
Section titled “Example 7 — Clean product and region labels in raw sales data”Goal: data/sales_raw.csv has 1,200 lines with region labels in many spellings and product names with stray spaces. Count the variants, clean them to canonical values, and check the result.
Step 1 — See why split(”,”) is not enough
Section titled “Step 1 — See why split(”,”) is not enough”sales_lines = Path("data/sales_raw.csv").read_text(encoding="utf-8").splitlines()print(len(sales_lines))print(sales_lines[9])print(len(sales_lines[9].split(",")))1201O000096,"January 7, 2023",C00173,S03,North,store,P008,Chef's Knife Set,Home,$129.95,1,0.0,129.9514The date "January 7, 2023" is in quotes because it contains a comma. split(",") ignores the quotes and gives 14 fields instead of 13. Every field after the date shifts one place, so fields[4] is the store id, not the region.
Step 2 — Parse the lines with the csv module
Section titled “Step 2 — Parse the lines with the csv module”import csv
records = list(csv.reader(sales_lines))header = records[0]data = records[1:]print(header[4], header[7])print(data[8][1], data[8][4], len(data[8]))region productJanuary 7, 2023 North 13csv.reader() understands quotes, so every line gives exactly 13 fields. list() collects all rows in a list. Module 07 covers the csv module in full. data[8] is file line 10, the line from step 1.
Step 3 — Look at the raw region variants
Section titled “Step 3 — Look at the raw region variants”raw_regions = []for record in data: raw_regions.append(record[4])variants = sorted(set(raw_regions))print(len(raw_regions), len(variants))print(variants[:8])print(variants[8:16])print(variants[16:])1200 23['', ' East ', ' North ', ' South ', ' West ', '-', 'EAST', 'East']['East ', 'N/A', 'NORTH', 'North', 'North ', 'SOUTH', 'South', 'South ']['WEST', 'West', 'West ', 'east', 'north', 'south', 'west']Four regions appear in 23 spellings: three missing-value tokens and the four names in lowercase, uppercase and with spaces. sorted(set(...)) lists each distinct value once, in order.
Step 4 — Map every variant to its canonical form
Section titled “Step 4 — Map every variant to its canonical form”clean_regions = []for raw_region in raw_regions: clean_regions.append(raw_region.strip().title())print(sorted(set(clean_regions)))print(clean_regions.count("North"), clean_regions.count("West"))print(clean_regions.count(""), clean_regions.count("N/A"), clean_regions.count("-"))['', '-', 'East', 'N/A', 'North', 'South', 'West']299 2687 7 3strip().title() maps all five spellings of each region to one canonical form. It leaves the tokens "", N/A and - unchanged. These 17 values mean “missing”, not a region. The list method count() counts the items equal to a value. Module 03 shows how to turn the tokens into None with an if statement.
Step 5 — Clean the product names and check them against the catalog
Section titled “Step 5 — Clean the product names and check them against the catalog”raw_products = []clean_products = []for record in data: raw_products.append(record[7]) clean_products.append(" ".join(record[7].split()))catalog = Path("data/products.csv").read_text(encoding="utf-8")print(len(set(raw_products)), len(set(clean_products)))print(repr(raw_products[38]), "->", repr(clean_products[38]))print("Non-Slip Yoga Mat" in catalog)90 30'Non-Slip Yoga Mat ' -> 'Non-Slip Yoga Mat'TrueStray spaces made 90 product spellings out of 30 products. After collapsing the spaces, exactly 30 names remain. A last check: each clean name should appear in data/products.csv, the official catalog. The in test on the whole catalog text confirms one name. Module 04 checks all 30 at once with sets.
Common mistakes:
- Parsing CSV lines with
split(","). Quoted fields with commas shift the columns without any error. Use thecsvmodule. - Using
title()on product names.Chef's Knife SetbecomesChef'S Knife Setand55-inch 4K Smart TVbecomes55-Inch 4K Smart Tv. These names were already in the right case; collapse the spaces and leave the case alone. - Treating
N/Aand-as a fifth and sixth region. A count by region would show them as real categories. Mark them as missing.
Pitfalls
Section titled “Pitfalls”| Mistake | Symptom | Fix |
|---|---|---|
s.strip() without assigning |
the value stays dirty | s = s.strip(); strings are immutable |
s[0] = "P" |
TypeError: 'str' object does not support item assignment |
build a new string: "P" + s[1:] |
s[len(s)] |
IndexError: string index out of range |
the last index is len(s) - 1, or use s[-1] |
s[11:12] for a 2-digit hour |
only one digit | the stop index is excluded; use s[11:13] |
name.strip(".csv") |
letters of the name disappear | name.removesuffix(".csv") |
split(" ") on messy spacing |
empty strings in the list | split() with no argument |
split(",") on a CSV line with quotes |
wrong number of fields, shifted columns | the csv module |
"21.7".isdigit() as a number test |
False for decimals and negatives |
try float() (module 06) |
title() on product names |
Chef'S, Smart Tv |
keep the original case; match against the catalog |
f"{rate * 100:.1%}" |
1926.0% |
% already multiplies by 100: f"{rate:.1%}" |
expecting f"{2.675:.2f}" to be 2.68 |
2.67 |
floats are binary; use decimal for exact money rounding |
| a width that is too small | a ragged table | the width is a minimum; make columns as wide as the longest value |
| header and rows with different widths | columns drift apart | use the same widths, ideally from variables |
reading a file without encoding= |
works on one machine, fails or garbles on another | always pass encoding="utf-8" (or the file’s encoding) |
| decoding latin-1 bytes as UTF-8 | UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 |
decode("latin-1") |
| decoding UTF-8 bytes as latin-1 | mojibake: Café |
decode as UTF-8; repair with .encode("latin-1").decode("utf-8") |
errors="ignore" to silence a decode error |
letters vanish without a warning | find the right encoding |
| comparing NFD and NFC text | "José" == "José" is False |
unicodedata.normalize("NFC", s) first |
| ASCII keys as stored values | Søren becomes Sren |
use accent-free keys only for matching |
Where this is used beyond data science
Section titled “Where this is used beyond data science”- Web development: a sign-up form strips and case-folds e-mail addresses before it checks for duplicates, and normalizes names to NFC before it saves them. URL slugs such as
p001-wireless-earbudscome fromlower(),replace(" ", "-")and an accent-free key. - Automation and scripting: a backup script builds file names with
f"backup_{n:04d}.tar", so they sort correctly, and a script that renames invoices slices dates out of the old names. - Logs and DevOps: an on-call engineer cuts the component, status code and duration out of log lines with
split(),find()and slicing, and prints an aligned summary in the terminal. - Tooling: command-line tools such as
pip listandgit log --onelineprint aligned columns with fixed widths, the same technique as the text tables of this module.
Summary
Section titled “Summary”- A
stris an immutable sequence of Unicode characters. Methods never change a string; they return a new one, so always assign the result. - Indexing starts at 0; negative indexes count from the end. A slice
s[start:stop:step]excludesstopand never raises anIndexError: out-of-range bounds are clipped. - Clean with
strip()," ".join(s.split()),replace(),removeprefix()and case methods. Usecasefold()for comparisons. Search within,find(),startswith()andcount(). split()andjoin()convert between a string and a list of pieces. Use thecsvmodule for real CSV files.- f-strings accept any expression,
!rforrepr()and=for debugging. The format spec grammar is[[fill]align][sign][z][#][0][width][grouping][.precision][type]. - For reports:
,.2ffor money,+.1%for growth,,for counts,<for text and>for numbers, with the same widths in the header and the rows. strholds code points;byteshold raw data.encode()anddecode()convert between them. Always name the encoding.- A
UnicodeDecodeErrormeans the wrong encoding. Mojibake means bytes were decoded with the wrong encoding without an error. - Normalize to NFC before you compare. Accent-free keys (NFKD + ASCII) are for matching only.
Self-check questions
Section titled “Self-check questions”Q1. What do "S01"[0], "S01"[-1] and "S01"[3] give?
Answer
'S', '1' and an IndexError: string index out of range. Valid indexes for a 3-character string are 0 to 2, or −1 to −3.
Q2. timestamp = "2024-05-09T15:20:00". Which slice gives "15:20", and why does timestamp[11:15] not work?
Answer
timestamp[11:16]. The stop index is excluded, so [11:15] gives only '15:2'. The length of a slice is stop - start, and "15:20" needs 5 characters.
Q3. After region = " west " and region.strip(), what is region? Why?
Answer
Still " west ". Strings are immutable, so strip() returns a new string, and this code throws it away. Write region = region.strip().
Q4. What is the difference between "maría josé ".split(" ") and "maría josé ".split()?
Answer
split(" ") cuts at every single space and gives ['maría', '', 'josé', ''], with empty strings. split() cuts at any run of whitespace and drops empty pieces: ['maría', 'josé'].
Q5. Write a format spec that shows 1950934.24 right-aligned in 16 characters with thousands separators and 2 decimals. What does f"{0.1856:+.1%}" show?
Answer
f"{1950934.24:>16,.2f}" gives ' 1,950,934.24'. The second gives '+18.6%': % multiplies by 100, .1 keeps one decimal, and + always shows the sign.
Q6. Why does f"{2.675:.2f}" show 2.67 and not 2.68?
Answer
The float 2.675 has no exact binary form. Python stores a value slightly below it (2.67499999…), and formatting rounds that value to 2.67. Round exact money with the decimal module or keep whole cents.
Q7. What is the difference between a str and a bytes object, and which method converts each into the other?
Answer
A str is a sequence of Unicode code points: text. A bytes object is a sequence of numbers from 0 to 255: raw data as stored in a file or sent over a network. str.encode(encoding) gives bytes; bytes.decode(encoding) gives str.
Q8. Reading a file with encoding="utf-8" raises UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9. What is the likely cause and fix?
Answer
The file is in a one-byte encoding such as latin-1 or cp1252, where 0xe9 is é. Read it with encoding="latin-1" (or "cp1252"), check a few known names, and save a UTF-8 copy.
Q9. A report shows Müller instead of Müller. What happened, and how do you repair the string?
Answer
The UTF-8 bytes of Müller were decoded as latin-1 (or cp1252), so each 2-byte letter became two characters. This is mojibake. Reverse it: text.encode("latin-1").decode("utf-8").
Q10. Two names both print as Zoë O'Brien, but == gives False. What do you check, and what do you do?
Answer
Check the lengths or repr(): one is probably NFD, with e plus a combining diaeresis. Normalize both with unicodedata.normalize("NFC", name) before you compare.
Q11. Why is title() safe for region labels such as north but not for product names such as chef's knife set?
Answer
title() starts a new word after any non-letter, including an apostrophe and a digit. north becomes North, but chef's becomes Chef'S and 4k smart tv becomes 4K Smart Tv. For product names, collapse spaces and match against the official catalog instead.
Track your progress
Section titled “Track your progress”Next steps
Section titled “Next steps”- Exercises: 26 exercises with hints and full solutions, from slicing ids to cleaning a whole sales file.
- Mini-project: clean the product names of a raw sales export, match them to the catalog and print an aligned report.
- Cheat sheet: every method, format spec and encoding fix of this module on one page.
- Next module: 03. Control flow teaches
if,match,forandwhile, so your cleaning code can make decisions and repeat itself.