01A.2 Numbers, Strings and Text
Almost everything an applied AI engineer touches is a number or a string: the ticket text a model must classify, the JSON payloads that carry requests and responses, log lines to parse, prompts to assemble, and the raw bytes that files and APIs exchange. This lesson takes Python's number types (int, float, Decimal, Fraction, complex) and its text types (str, bytes) and builds the working text toolbox on top of them: slicing, formatting, Unicode and encodings, regular expressions and the standard-library recipes for cleaning and extracting text. By the end you can parse a messy support ticket into fields, format a readable report, understand why len(text) is not the token count, and know exactly where floats and encodings will bite you in production.
What you'll learn
- How Python's number types differ: arbitrary-precision
int, IEEE-754floatand its surprises,boolas anint,DecimalandFractionfor exact arithmetic, andcomplexat awareness level - Whole-number division, remainders and
divmod, especially with negative numbers;round()'s banker's rounding; themathmodule, seededrandom, andstatistics - Strings as immutable sequences: quotes, escape sequences, raw strings, indexing and slicing,
len, concatenation vsjoin, repetition, comparison and sorting - The string methods that do 95% of real work (
strip,split,join,replace,startswith,partition,casefoldand friends), plus multi-line text andtextwrap - f-strings and the format-spec mini-language (width, alignment, precision, thousands separators,
!r/!aconversions,=and nesting), and how to recognisestr.formatand%in older code andt"..."template strings in new code - Unicode and encodings done properly: characters vs bytes, code points, UTF-8,
str.encode/bytes.decode,UnicodeDecodeError, normalization (NFC vs NFD), emoji and grapheme clusters, BOMs and line endings - Regular expressions with
re: the core functions that matter, pattern syntax, greedy vs lazy matching, catastrophic backtracking, when not to reach for a regex, and ten practical patterns - Text-processing recipes you will reuse constantly: word counts, whitespace cleaning, slugifying, log-line field extraction,
string.Templatetemplating anddifflib - A running example: parsing a raw support-ticket string into fields, normalising its text and matching it with keywords
What you don't need
- Any prior Python beyond lesson 01A.1 (running files, variables, basic types). Control flow and functions get their own lesson (01A.3); this lesson uses simple
forloops anddefwhere needed and flags them. - An API key or any network access. Everything here is pure standard library and runs offline. No API key needed.
Setup
You need Python 3.11 or newer and a terminal. If you haven't set up your computer yet, start with 00.1: Setting up your computer. To install Python, the recommended route is uv:
uv python install 3.13 # installs a managed Python; uv run uses it automatically
uv run script.py # run a file with the project interpreterOr download an installer from python.org, or use your operating system's package manager. Any of these is fine; check yours with:
python3 --version # macOS/Linux; on Windows try: py --versionWhat you must be able to do after this lesson#
- Explain why float arithmetic surprises and when to use Decimal
- Slice, search and clean strings with the common string methods
- Format output with f-strings and format specs
- Explain the difference between characters and bytes and encode text as UTF-8
- Write a simple regular expression and test it
- Build a small text-cleaning function
Why this matters for an AI engineer#
You will not train models, but every LLM app you build is a text-and-numbers pipeline. These are the moments where this lesson's details decide whether your code works:
| You'll hear... | You'll understand it after... |
|---|---|
| "The invoice total was off by one cent." | 1.6 Decimal and Fraction |
"0.1 + 0.2 != 0.3 corrupted our confidence scores." |
1.2 float |
"len(text) says 500 but the tokenizer billed 900 tokens." |
4.7 len() counts characters, not tokens |
| "The model wrapped its JSON in a markdown code fence again." | 5.5 Ten practical patterns and 03.4 |
| "Two users' names looked identical but weren't — one had a Cyrillic 'а'." | 4.4 Normalization and 12.5 |
| "The regex hung the worker on adversarial input." | 5.3 Greedy vs lazy, and catastrophic backtracking |
| "Hindi text costs three times the tokens of English." | 4.7 and 02.2, Part 8 |
| "Images in API requests are just base64 strings." | 4.2 and 03.6 |
| "Dates in the logs come in three formats." | 6.3 Extracting fields from log lines |
Part 1: Numbers#
Python has four built-in numeric types you'll meet constantly — int, float, bool and complex — plus two standard-library types for exact arithmetic, decimal.Decimal and fractions.Fraction. Choosing the right one is a real engineering decision, especially for money.
1.1 int: whole numbers of any size#
Python's int is a whole number type with a property most languages lack: it is arbitrary precision. It grows as large as your computer's memory allows, instead of overflowing at 32 or 64 bits.
import math
big = 10 ** 100
print("10**100 =", big)
print("digits:", len(str(big)))
print("2**64 =", 2**64)
print("20! =", math.factorial(20))10**100 = 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
digits: 101
2**64 = 18446744073709551616
20! = 2432902008176640000You can write integers in decimal, hexadecimal (0x), binary (0b) and octal (0o), and use _ as a visual separator:
million = 1_000_000 # underscores are ignored: 1000000
print(million, 0xFF, 0b1010, 0o17)1000000 255 10 15One limit worth knowing: converting a huge int to or from a decimal string is capped. Since Python 3.11, sys.get_int_max_str_digits() returns 4300 by default — int↔str conversions on numbers with more digits raise ValueError, a defence against denial-of-service via inputs like int("9" * 10**7). sys.set_int_max_str_digits() raises the cap when you genuinely need it:
import sys
print(sys.get_int_max_str_digits()) # 4300 by default (Python 3.11+)
try:
str(10 ** 5000)
except ValueError as e:
print("str(10**5000) ->", type(e).__name__)4300
str(10**5000) -> ValueErrorOrdinary arithmetic is unaffected — the cap applies only at the int↔str boundary, which is why len(str(big)) above works fine at 101 digits.
Arithmetic is the familiar + - * / **, plus // (floor division) and % (remainder), covered next.
1.2 float: binary fractions and their surprises#
A float is a double-precision floating-point number: 64 bits following the IEEE 754 standard, the same format JavaScript's number, Java's double, PHP's float and most databases' DOUBLE PRECISION/DOUBLE use. The name is short for floating point: the binary point "floats" to wherever the 53 significant bits need it, which is what lets one format hold both 1e-300 and 1e300.
The critical fact: floats store numbers in binary, and most decimal fractions (0.1, 0.2, 0.3, prices like 19.99) have no exact binary representation — just as 1/3 has no exact decimal representation. So 0.1 + 0.2 is not exactly 0.3:
import math
print("0.1 + 0.2 =", repr(0.1 + 0.2))
print("0.1 + 0.2 == 0.3 ?", (0.1 + 0.2) == 0.3)
print("math.isclose:", math.isclose(0.1 + 0.2, 0.3))0.1 + 0.2 = 0.30000000000000004
0.1 + 0.2 == 0.3 ? False
math.isclose: TrueTwo more float facts worth memorising:
floatcan represent infinity and not-a-number (nan), values nointcan hold:
print(1e308 * 10) # overflow -> inf
print(float("inf"), float("-inf"), float("nan"))
print(float("inf") == float("inf")) # True
print(float("nan") == float("nan")) # False — nan is never equal to anything, even itself
print(math.isnan(float("nan"))) # the correct way to test for naninf
inf -inf nan
True
False
True- Division by zero raises
ZeroDivisionErrorfor bothintandfloatin Python —1.0 / 0.0does not silently produceinfthe way C and JavaScript do. If you want infinity, writefloat("inf")explicitly.
try:
1.0 / 0.0
except ZeroDivisionError as e:
print("float 1.0/0.0 ->", type(e).__name__, e)float 1.0/0.0 -> ZeroDivisionError division by zero(The message wording varies by Python version — 3.13 and earlier print float division by zero here; 3.14 prints division by zero. Catch the exception type; never match on its message text.)
1.3 Floor division, remainder and divmod#
// is floor division (round down to the nearest whole number) and % is the remainder. With positive operands they behave as you expect; with negatives they follow a consistent rule that surprises people coming from C or JavaScript.
for a, b in [(7, 2), (-7, 2), (7, -2), (-7, -2)]:
print(f"{a} // {b} = {a // b} {a} % {b} = {a % b} divmod = {divmod(a, b)}")
print("identity check:", (-7 // 2) * 2 + (-7 % 2) == -7)7 // 2 = 3 7 % 2 = 1 divmod = (3, 1)
-7 // 2 = -4 -7 % 2 = 1 divmod = (-4, 1)
7 // -2 = -4 7 % -2 = -1 divmod = (-4, -1)
-7 // -2 = 3 -7 % -2 = -1 divmod = (3, -1)
identity check: TrueThe rule: // rounds towards negative infinity, and % always returns a result with the sign of the divisor (the right operand). So -7 % 2 is 1, not -1 — Python's % is a mathematical modulo, not a truncation remainder. This is actually convenient: "is this number even?" is n % 2 == 0 for negative n too, and cyclic indexing (items[-1 % len(items)]-style arithmetic) works uniformly. divmod(a, b) returns the pair (a // b, a % b) in one call — useful for splitting totals into groups and leftovers (e.g. "3 cases, 2 per page → 1 leftover").
1.4 Exponents, math, rounding and formatting#
**is exponentiation:2 ** 10 == 1024, and it binds tighter than unary minus on the left (-2**2 == -4, because the exponent is evaluated first — write(-2)**2if you mean 4).//on floats works too (7.9 // 2 == 3.0) but returns a float;math.floor/math.ceil/math.truncare the explicit tools.
import math
print(math.sqrt(2), math.pi)
print(math.floor(3.7), math.ceil(3.2), math.trunc(-3.7))
print(math.gcd(48, 180), math.prod([2, 3, 4]), math.hypot(3, 4))
print(math.isfinite(1e308 * 10), math.isinf(float("inf")))1.4142135623730951 3.141592653589793
3 4 -3
12 24 5.0
False Trueround() uses banker's rounding (round-half-to-even), not "round half up":
for x in [0.5, 1.5, 2.5, 3.5, -0.5, -1.5, -2.5]:
print(f"round({x}) = {round(x)}")
print("round(2.675, 2) =", round(2.675, 2))
print("round(1234.5678, 1) =", round(1234.5678, 1))round(0.5) = 0
round(1.5) = 2
round(2.5) = 2
round(3.5) = 4
round(-0.5) = 0
round(-1.5) = -2
round(-2.5) = -2
round(2.675, 2) = 2.67
round(1234.5678, 1) = 1234.6Two subtleties: round(2.675, 2) gives 2.67, not 2.68, because 2.675 cannot be stored exactly — it is really 2.67499999.... And round() on an int with no second argument returns an int. If you need commercial "half up" rounding (invoices, tax), that's a Decimal job — see 1.6.
For display, round() is rarely what you want — f-string format specs (Part 3) handle precision and thousands separators.
1.5 bool is an int#
bool is a subclass of int: True is 1 and False is 0 for arithmetic, but type(True) is bool. This is why True + True == 2 and isinstance(True, int) is True.
print("True + True =", True + True)
print("isinstance(True, int):", isinstance(True, int))
print("True == 1:", True == 1, "| type:", type(True))True + True = 2
isinstance(True, int): True
True == 1: True | type: <class 'bool'>1.6 Decimal and Fraction: exact arithmetic#
When approximate floats aren't good enough — money is the canonical case — Python's standard library offers two exact types.
decimal.Decimal stores numbers in base-10 exactly as written, like a calculator or a database NUMERIC/DECIMAL column:
from decimal import Decimal, ROUND_HALF_UP
price = Decimal("19.99")
qty = Decimal("3")
print("Decimal('19.99') * Decimal('3') =", price * qty)
print("as floats: ", 19.99 * 3)
print("Decimal('0.1') + Decimal('0.2') =", Decimal("0.1") + Decimal("0.2"))
print("equals Decimal('0.3')? ", Decimal("0.1") + Decimal("0.2") == Decimal("0.3"))Decimal('19.99') * Decimal('3') = 59.97
as floats: 59.97
Decimal('0.1') + Decimal('0.2') = 0.3
equals Decimal('0.3')? TrueNote the constructor takes a string (Decimal("19.99")), never a float: Decimal(0.1) faithfully reproduces the float's binary error as a long ugly decimal. Decimal arithmetic is exact to the context's precision (28 significant digits by default) and supports quantize for rounding to cents:
subtotal = Decimal("45.00") + Decimal("19.99") + Decimal("7.50")
tax = (subtotal * Decimal("0.0825")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
print("subtotal =", subtotal, "| tax =", tax, "| total =", subtotal + tax)subtotal = 72.49 | tax = 5.98 | total = 78.47fractions.Fraction stores exact rational numbers — Fraction(1, 3) is literally one third, not 0.333...:
from fractions import Fraction
print(Fraction(1, 3) + Fraction(1, 6)) # exact: 1/2
print(Fraction("0.1")) # 1/10 — exact
print(Fraction(0.1)) # ugly: the float's exact binary value
print(float(Fraction(1, 3))) # 0.3333333333333333 when you need a float1/2
1/10
3602879701896397/36028797018963968
0.3333333333333333Decision table:
| Situation | Use | Why |
|---|---|---|
| Money, invoices, tax, any "must add to the cent" | Decimal (from strings) |
Exact base-10, configurable rounding |
| Exact ratios, probabilities as fractions, school math | Fraction |
Exact rational arithmetic |
| Measurements, scores, ML features, anything scientific | float + math.isclose |
Fast, hardware-native, standard everywhere |
| Counts, indices, sizes | int |
Exact, arbitrary precision |
1.7 random and statistics#
random is the standard-library pseudo-random number generator (PRNG). For anything non-security (simulations, shuffling test data, jitter), it's fine; for tokens or passwords use secrets (Module 01A.7 covers it).
import random
random.seed(42) # same seed -> same sequence, every run
print(random.random()) # float in [0.0, 1.0)
print(random.randint(1, 6))
items = ["alpha", "beta", "gamma", "delta"]
random.shuffle(items)
print(items)0.6394267984578837
1
['beta', 'delta', 'alpha', 'gamma']Seeding makes demos and tests reproducible — always random.seed(...) (or better, use a local rng = random.Random(42) so you don't disturb global state) when output must be deterministic.
statistics gives you mean, median, stdev, variance etc. over any iterable of numbers — including Decimal:
import statistics
scores = [82, 91, 78, 85, 88, 90, 76, 84]
print(statistics.mean(scores), statistics.median(scores), round(statistics.stdev(scores), 2))84.25 84.5 5.42You'll rarely compute statistics by hand in AI work — but statistics.mean on a list of per-request latencies is exactly the kind of quick analysis it exists for. For serious data work, pandas (Module 01B.11) owns this space.
1.8 complex numbers (a five-minute awareness)#
complex numbers (3 + 4j) exist for signal processing and some math libraries; you will essentially never use them in applied AI work. Know they exist, that abs(z) gives the magnitude, and move on:
z = 3 + 4j
print(z, "| real:", z.real, "| imag:", z.imag, "| abs:", abs(z))(3+4j) | real: 3.0 | imag: 4.0 | abs: 5.0Part 2: Strings#
A str in Python 3 is text: a sequence of Unicode characters. It is not bytes — more on that distinction in Part 4, because it is the single most common source of bugs in real pipelines. For now, treat a string as "a piece of text you can index, slice and search".
2.1 Quotes, escapes and raw strings#
You can write strings with single quotes '...', double quotes "..." or triple quotes """...""". Triple-quoted strings can span lines and keep the line breaks:
s1 = 'single quotes'
s2 = "double quotes"
s3 = """triple-quoted
spans
lines"""
print(repr(s3))
print("len(s3):", len(s3))'triple-quoted\nspans\nlines'
len(s3): 25Pick whichever quote style avoids escaping: "it's" needs no escape inside double quotes, and 'say "hi"' needs none inside single quotes. PEP 8 leaves the choice to you for single-line strings — pick one style and stick to it (it only mandates double quotes for triple-quoted strings and docstrings). Formatters like ruff format normalise to double quotes; either way, choose the quote style that avoids escapes.
Escape sequences are backslash codes inside a normal string: \n newline, \t tab, \\ backslash, \" and \' quotes, \r carriage return, \0 NUL. They are interpreted when the literal is created:
print("a\tb\nc\"d")
print("backslash: \\")a b
c"d
backslash: \Raw strings (r"...") turn escape processing off — the backslash stays a literal backslash. You need them constantly for regex patterns and Windows paths:
win = r"C:\Users\poovarasu\file.txt"
pat = r"\d+\.\d+"
print(win)
print(pat)C:\Users\poovarasu\file.txt
\d+\.\d+2.2 Strings are immutable#
You cannot change a character of a string in place — s[0] = "H" raises TypeError. Every "modification" produces a new string:
s = "hello"
try:
s[0] = "H"
except TypeError as e:
print("s[0] = 'H' ->", type(e).__name__, ":", e)
print("the fix:", s.replace("h", "H", 1), "|", "H" + s[1:])s[0] = 'H' -> TypeError : 'str' object does not support item assignment
the fix: Hello | HelloImmutability is why strings are safe to use as dictionary keys and set members, and why "append to a string" in a loop (s += piece) is a different performance story than appending to a list — covered in 6.6.
2.3 Indexing and slicing#
Indexing gives you one character; slicing gives you a substring. Indices start at 0, and negative indices count from the end (-1 is the last character):
text = "support ticket"
print("text[0]:", text[0], "| text[-1]:", text[-1], "| len:", len(text))
print("text[0:7]:", text[0:7], "| text[:7]:", text[:7], "| text[8:]:", text[8:])
print("text[-7:]:", text[-7:])
print("text[::2]:", text[::2])
print("text[::-1]:", text[::-1])text[0]: s | text[-1]: t | len: 14
text[0:7]: support | text[:7]: support | text[8:]: ticket
text[-7:]: ticket
text[::2]: spottce
text[::-1]: tekcit troppusA slice s[start:stop:step] includes start and excludes stop. Omitted parts default sensibly: s[:n] is "first n", s[n:] is "from n on", s[-n:] is "last n". The step ::2 takes every second character; ::-1 reverses.
Two behaviours that prevent bugs:
- Out-of-range slices don't raise.
text[100:]returns""— onlytext[100](single index) raisesIndexError. Slicing is forgiving, indexing is strict. - A slice where start > stop returns
"", not an error:text[7:2] == "".
2.4 Length, concatenation, join and repetition#
len(s) returns the number of characters (code points — Part 4 explains why that isn't always "what you see"). Concatenation with + works but is the wrong tool for many pieces — str.join is the idiomatic way:
parts = ["ticket", "billing", "urgent"]
print(" ".join(parts))
print("-".join(parts))
print("ticket" + " " + "billing")
print("=" * 20)
print("ab" * 3)ticket billing urgent
ticket-billing-urgent
ticket billing
====================
abababsep.join(iterable)putssepbetween elements — and it's the fast, readable way to build text from a list.+concatenates two strings; fine for two or three pieces, quadratic-risky in loops (6.6).*repeats:"=" * 20makes a divider line,"ab" * 3makes"ababab".
Comparison and membership: strings compare lexicographically ("apple" < "banana"), and in checks substring presence. Sorting is by code point, so uppercase sorts before lowercase — 'Apple' < 'banana' is True:
print("apple" < "banana", "|", "Apple" < "banana")
print(sorted(["banana", "Apple", "cherry"]))
print(sorted(["Banana", "apple", "Cherry"]))
print(sorted(["Banana", "apple", "Cherry"], key=str.lower))
print("resolved" in "Your ticket has been resolved.")True | True
['Apple', 'banana', 'cherry']
['Banana', 'Cherry', 'apple']
['apple', 'Banana', 'Cherry']
TrueThe third sorted is the lesson: plain sorting puts all uppercase before all lowercase ('Banana' < 'Cherry' < 'apple'), because it compares code points. key=str.lower (or str.casefold) sorts the way humans expect. For user-facing ordering — names, categories, search results — always sort with a case-insensitive key.
2.5 The string methods that matter#
str has ~45 methods. You need maybe 25 of them daily. Here is the working set, grouped by job, all demonstrated on real output.
Case:
t = " Hello World "
print(repr(t.strip()), "|", repr(t.lower()), "|", repr(t.upper()))
print(repr(t.title()), "|", repr(t.capitalize()))
print("'Straße'.casefold():", "Straße".casefold(), "vs .lower():", "Straße".lower())'Hello World' | ' hello world ' | ' HELLO WORLD '
' Hello World ' | ' hello world '
'Straße'.casefold(): strasse vs .lower(): straßeNote strip() removes leading/trailing whitespace but not the interior; title() and capitalize() keep surrounding whitespace. casefold() is the aggressive lowercase for comparison — it maps ß→ss (German sharp s) so "STRASSE".casefold() == "Straße".casefold(); .lower() leaves ß alone. For matching user input, casefold() is almost always the right choice (covered again in 4.5).
Split family:
line = "2026-11-06 ERROR disk full on node-3"
print(line.split())
print(line.split(None, 2))
print("a,b,,c".split(","))
print("l1\nl2\r\nl3".splitlines())
print("a,b,c,d".rsplit(",", 1))['2026-11-06', 'ERROR', 'disk', 'full', 'on', 'node-3']
['2026-11-06', 'ERROR', 'disk full on node-3']
['a', 'b', '', 'c']
['l1', 'l2', 'l3']
['a,b,c', 'd']split()with no argument splits on any whitespace run and discards empties — the default you want for prose.split(sep)splits on that exact separator and keeps empty fields ("a,b,,c"→['a','b','','c']) — that's what CSV-like parsing needs.split(None, maxsplit)limits the number of splits;rsplitworks from the right.splitlines()handles\n,\r\nand\runiformly — use it for file/log text instead ofsplit("\n").
Search family:
msg = "Your ticket TKT-1042 has been resolved."
print("find:", msg.find("TKT"), "| index:", msg.index("TKT"))
print("find missing:", msg.find("NOPE"), "<- -1")
try:
msg.index("NOPE")
except ValueError as e:
print("index missing ->", type(e).__name__, e)
print("count 't':", msg.count("t"))
print("startswith:", msg.startswith("Your"), "| endswith:", msg.endswith("resolved."))find: 12 | index: 12
find missing: -1 <- -1
index missing -> ValueError substring not found
count 't': 2
startswith: True | endswith: Truefind returns -1 on a miss; index raises ValueError. Pick find when absence is normal, index when absence is a bug. in ("TKT" in msg) is the boolean form and what you reach for most.
Replace and partition:
print("a-b-c".replace("-", "_"))
print("aaa".replace("a", "b", 2))
print("user=bob;role=admin".partition("="))
print("path/to/file.txt".rpartition("/"))
print(repr("xxhelloxx".strip("x")))a_b_c
bba
('user', '=', 'bob;role=admin')
('path/to', '/', 'file.txt')
'hello'partition(sep) splits into (before, sep, after) at the first occurrence — perfect for "key=value" pairs; rpartition uses the last (for path/to/file → directory/file). replace(old, new, count) limits replacements. strip(chars) strips any of the given characters from both ends.
Prefixes, suffixes and character translation:
print("TKT-1042".removeprefix("TKT-"))
print("report.csv".removesuffix(".csv"))
print("keep-me".removesuffix(".csv"))
print("don't stop".translate(str.maketrans("", "", "'")))
print("hello".translate(str.maketrans("el", "ip")))1042
report
keep-me
dont stop
hipporemoveprefix/removesuffix (Python 3.9+) strip one exact affix — safer than lstrip/rstrip, which strip any character from a set repeatedly, and simpler than regex for a known prefix like "TKT-" or an extension like ".csv". No match returns the string unchanged. translate/str.maketrans do character-level substitution or deletion without regex: the two-string form maps char→char ("el"→"ip" turns hello into hippo), a third string lists characters to delete, and a dict argument maps chars or ordinals to replacements or None for deletion — handy for stripping punctuation before matching.
Predicates and padding:
print("123".isdigit(), "|", "12a".isdigit(), "|", "abc".isalpha(), "|", "a1".isalnum())
print(" ".isspace(), "|", "".isspace())
print("7".zfill(3), "|", "-42".zfill(5))
print("[" + "hi".center(10, "-") + "]")True | False | True | True
True | False
007 | -0042
[----hi----]isdigit/isalpha/isalnum/isspace/isnumeric validate character classes without regex — but remember isdigit is True for superscripts like ² while isdecimal is stricter; for "is this a normal integer" prefer str.isdecimal() or try int(s) (see exercises). zfill pads with zeros respecting sign; ljust, rjust and the centring method (spelled "center" in code) pad with any fill character.
2.6 Multi-line text and textwrap#
Triple-quoted strings are the easy way to embed multi-line text (prompts, templates, reports). For display wrapping of long paragraphs, textwrap does it properly:
import textwrap
para = ("Retrieval-augmented generation pipelines ingest documents, "
"chunk them into overlapping windows, embed each chunk, and "
"store the vectors for later similarity search.")
print(textwrap.fill(para, width=50))
print("---")
print(textwrap.shorten("This is a very long sentence that keeps going and going.",
width=40, placeholder="..."))
print("---")
print(textwrap.indent("line one\nline two", "> "))Retrieval-augmented generation pipelines ingest
documents, chunk them into overlapping windows,
embed each chunk, and store the vectors for later
similarity search.
---
This is a very long sentence that...
---
> line one
> line twofill re-wraps to a width; shorten truncates on a word boundary; indent prefixes lines — the same job textwrap.indent does for code blocks and quoted replies. textwrap.dedent removes common leading whitespace, which is how you write indented triple-quoted strings inside functions without the indent becoming part of the text.
Part 3: Formatting text#
Turning values into readable text is a daily job: log lines, report tables, error messages, prompt assembly. Python gives you f-strings (the modern default), the older str.format and % (recognise them, don't write them), plus repr, str, pprint and a few helpers.
3.1 f-strings#
An f-string is a string literal prefixed with f whose {...} parts are evaluated as Python expressions at runtime:
name, age, score = "Ada", 36, 98.765
pi = 3.141592653589793
print(f"{name} is {age} years old")
print(f"pi={pi:.2f} pi={pi:.10f}")
print(f"{name=}, {age=}") # self-documenting, Python 3.8+
print(f"{score!r}") # !r applies repr()
print(f"{'café'!a}") # !a applies ascii(): ASCII-safe reprAda is 36 years old
pi=3.14 pi=3.1415926536
name='Ada', age=36
98.765
'caf\xe9'{expr}embeds any expression:f"total: {price * qty:.2f}",f"{items[0]}", even a function callf"{len(text):,} chars".{expr!s},{expr!r}and{expr!a}applystr(),repr()andascii()—!rshows quotes and escapes (f"{text!r}"gives'line1\nline2'), and!aproduces ASCII-safe output (f"{'café'!a}"gives'caf\xe9') for text bound for legacy encodings or byte-oriented logs.{name=}(3.8+) printsname='Ada'— great for debugging and log lines, because the variable name comes along for free.- f-strings are evaluated each time the line runs, left to right. A walrus assignment inside one needs its own parentheses —
f"{(n := len(text))} chars, {n} again"— because a bare:inside{...}starts the format spec (f"{x := 1}"does not assign; it applies the format spec= 1tox, which gives a padded number for anintand aValueErrorfor astr). That is a good reason to keep f-strings for formatting and logic outside them.
3.2 The format-spec mini-language#
Inside {expr:SPEC} the part after the colon is a format specification: [[fill]align][sign][#][0][width][,][.precision][type]. You use a small subset constantly:
price = 1234567.891
print(f"{price:,.2f}") # thousands separator + 2 decimals
print(f"{price:_.2f}") # underscore separator
print(f"{12345:>10}|") # right-align, width 10
print(f"{'left':<10}|{'right':>10}|")
print(f"{'^':^7}") # centred
print(f"{255:#x} {255:#b} {255:#o}") # 0x / 0b / 0o prefixes
print(f"{0.856:.1%}") # percent
print(f"{3.14159:.3e}") # scientific
print(f"{42:05d}") # zero-pad to width 5
print(f"{3.14159:+.2f}") # always show sign
print(f"{1000000:,}")1,234,567.89
1_234_567.89
12345|
left | right|
^
0xff 0b11111111 0o377
85.6%
3.142e+00
00042
+3.14
1,000,000The mini-language is a table you learn once:
| Spec | Meaning | Example |
|---|---|---|
> < ^ |
align right / left / centre | {x:>8} |
= |
pad after sign (numbers) | {x:=+8} |
+ - |
sign: always / only minus / space-for-positive | {x:+.2f} |
# |
alternate form (0x, 0b, keep trailing point) |
{x:#x} |
0 |
zero-pad to width | {x:05d} |
, _ |
thousands separator | {x:,.0f} |
.N |
precision (decimals, or max chars for strings) | {x:.2f}, {s:.3} |
d f e g s % x b o |
type | {x:.1%}, {n:x} |
Specs can be nested: f"{value:{width}.{precision}f}" where width/precision are variables — that's how you build tables with dynamic column widths.
3.3 str.format and percent formatting: recognise, don't write#
You'll meet two older styles in existing code. str.format uses {} placeholders with optional names:
print("{}, {}".format("old", "style"))
print("{name} is {age}".format(name="Ada", age=36))
print("%s is %d years old" % ("Ada", 36))old, style
Ada is 36
Ada is 36 years old% formatting is the oldest (C-style): %s string, %d int, %f float, %% literal percent. Both still work but are effectively frozen — no new features, worse readability, and % has real footguns ("%d" % "5" raises, % collides with the modulo operator in complex expressions). Write f-strings; read the others. Module 04's prompt-templating lesson (04.10 §2.3) covers when str.format-style deferred substitution is actually the right tool — for templates rendered later, not for one-off messages.
3.4 repr, str and pprint#
str(x) is "the friendly text" (what print shows); repr(x) is "the unambiguous developer text" — quotes around strings, \n visible, type info where useful. For containers they often coincide because dict.__repr__ shows valid Python syntax:
s = "line1\nline2"
d = {"a": 1, "b": [1, 2]}
print("str(s):", str(s))
print("repr(s):", repr(s))
print("str(d):", str(d))
print("repr(d):", repr(d))str(s): line1
line2
repr(s): 'line1\nline2'
str(d): {'a': 1, 'b': [1, 2]}
repr(d): {'a': 1, 'b': [1, 2]}The difference that matters: repr of a string quotes and escapes it, so repr("a'b") gives "a'b" with double quotes — you can paste repr output back into Python and get the same value. That's why tracebacks and logs use repr (!r in f-strings). For nested data structures too big for one line, pprint pretty-prints with sorting and wrapping:
import pprint
data = {"tickets": [{"id": "TKT-1", "tags": ["billing", "urgent"]},
{"id": "TKT-2", "tags": ["bug"]}], "count": 2}
pprint.pprint(data, width=60){'count': 2,
'tickets': [{'id': 'TKT-1', 'tags': ['billing', 'urgent']},
{'id': 'TKT-2', 'tags': ['bug']}]}pprint.pformat returns the string instead of printing — useful when you want the formatted text inside a log record or an error message.
3.5 Building tables#
Reports and CLI output are just formatted strings. Compute column widths first, then emit rows — this is the pattern behind every hand-rolled table you'll write:
rows = [("ID", "Category", "Priority"), # header first, so widths cover it too
("TKT-1041", "billing", "high"),
("TKT-1042", "bug", "low"),
("TKT-1043", "account", "medium")]
widths = [max(len(r[i]) for r in rows) for i in range(3)]
for n, (tid, cat, pri) in enumerate(rows): # enumerate gives (index, item) pairs: 01A.3
print(f"{tid:<{widths[0]}} {cat:<{widths[1]}} {pri:<{widths[2]}}".rstrip())
if n == 0:
print(" ".join("-" * w for w in widths)) # rule under the headerID Category Priority
-------- -------- --------
TKT-1041 billing high
TKT-1042 bug low
TKT-1043 account mediumThe two-pass pattern is the point: measure the widest cell in each column (header included), then pad every cell to that width with a nested spec ({cat:<{widths[1]}}, see 3.2). .rstrip() removes the padding after the last column.
3.6 t-strings (Python 3.14+): awareness#
Python 3.14 added template strings (PEP 750): a literal prefixed with t instead of f. It looks like an f-string, but it does not produce a str. It produces a string.templatelib.Template object that keeps the literal pieces and the interpolated values separate, so a library can decide what to do with each before anything is joined:
# tstring_demo.py (needs Python 3.14 or newer)
from string.templatelib import Interpolation, Template
user_text = "Ada <b>"
total = 59.97
t = t"Hello {user_text}! Total: {total:.2f}"
print(type(t).__name__, isinstance(t, str))
print(t.strings)
print([(i.expression, i.value, i.format_spec) for i in t.interpolations])
def render_escaped(template: Template) -> str:
"""Join a template, escaping only the interpolated values."""
parts = []
for item in template: # literal strings and Interpolation objects, in order
if isinstance(item, Interpolation):
value = format(item.value, item.format_spec)
parts.append(value.replace("<", "<").replace(">", ">"))
else:
parts.append(item)
return "".join(parts)
print(render_escaped(t))Template False
('Hello ', '! Total: ', '')
[('user_text', 'Ada <b>', ''), ('total', 59.97, '.2f')]
Hello Ada <b>! Total: 59.97Why you might care: the trusted text (your literals) and the untrusted text (user_text) arrive separately, so a library can escape HTML, quote SQL or sanitise prompt fragments per value, which an f-string — already flattened into one str — cannot. Two honest limits: a Template does no formatting or escaping by itself (somebody has to write the renderer, as above), and it is a different type, so "x" + t raises TypeError and print(t) does not show the joined text. It needs 3.14+; this path targets 3.11+, so you will not rely on it here — keep writing f-strings for messages and the approaches in 04.10 for prompt templates, and recognise t"..." when a library's docs use it.
Part 4: Unicode and encodings#
This is the part of the lesson that matters most for LLM work. Every prompt you send, every document you ingest, every API response you parse is text that must survive a journey from characters to bytes and back — often across systems that disagree about how to do it. Get this wrong and you get mojibake, crashes, or security bugs.
4.1 Characters, code points and UTF-8#
Three layers to keep separate:
| Layer | What it is | Python type | Example |
|---|---|---|---|
| Character / code point | One Unicode symbol | str element |
"é" |
| Encoded bytes | The code point stored as 1–4 bytes | bytes |
b'\xc3\xa9' |
| Grapheme cluster | What a human sees as one character (may be several code points) | not a Python type | "🇮🇳", "👩🏽💻" |
Unicode assigns every character a code point — a number like U+00E9 for é. ord(c) gives you the code point of a one-character string, chr(n) the reverse:
print(ord("A"), chr(65), chr(0x1F600), ord("é"))
s = "héllo"
print("len(s):", len(s), "chars")
print("code points:", [hex(ord(c)) for c in s])65 A 😀 233
len(s): 5 chars
code points: ['0x68', '0xe9', '0x6c', '0x6c', '0x6f']UTF-8 is the encoding that turns code points into bytes: ASCII characters (0–127) take 1 byte, most other letters 2, CJK and emoji 3–4. It is the standard — every web page, JSON payload and API you will touch uses it.
print("utf-8 bytes:", "héllo".encode("utf-8"))
print("byte count:", len("héllo".encode("utf-8")), "vs char count:", len("héllo"))
print("é utf-8:", "é".encode("utf-8"), "= 2 bytes")
print("🎉 utf-8:", "🎉".encode("utf-8"), "= 4 bytes")utf-8 bytes: b'h\xc3\xa9llo'
byte count: 6 vs char count: 5
é utf-8: b'\xc3\xa9' = 2 bytes
🎉 utf-8: b'\xf0\x9f\x8e\x89' = 4 bytesflowchart LR
T["str: 'café'"] -- "encode('utf-8')" --> B["bytes: b'caf\\xc3\\xa9'"]
B -- "send over network / write file" --> W["wire / disk"]
W -- "decode('utf-8')" --> T2["str: 'café'"]
B -.->|"decode('latin-1')"| M["mojibake: 'café'"]4.2 Encoding and decoding: str, bytes and bytearray#
str.encode(encoding) turns text into bytes; bytes.decode(encoding) turns bytes back into text. str.encode()/bytes.decode() default to UTF-8, but open()'s default is locale-dependent on Python ≤3.14 (UTF-8 on macOS/Linux, often a legacy code page on Windows) — always pass encoding="utf-8" explicitly to open(), as lesson 01A.9 makes a hard rule.
b = "café".encode("utf-8")
print("roundtrip:", b.decode("utf-8"))
raw = b"hello"
print(type(raw), raw[0], raw[0:2]) # bytes index to ints, slice to bytes
ba = bytearray(b"abc")
ba[0] = ord("A")
print("bytearray mutable:", ba)
try:
raw[0] = 65
except TypeError as e:
print("bytes immutable ->", type(e).__name__, e)
print("hex dump:", raw.hex())
print("fromhex:", bytes.fromhex("68 65 6c 6c 6f"))roundtrip: café
<class 'bytes'> 104 b'he'
bytearray mutable: bytearray(b'Abc')
bytes immutable -> TypeError 'bytes' object does not support item assignment
hex dump: 68656c6c6f
fromhex: b'hello'bytesis immutable (likestr);bytearrayis the mutable counterpart — useful for building binary data incrementally.- Indexing
bytesgives integers (raw[0]is104, the ASCII code forh), not one-bytebytesobjects — a difference fromstrwheres[0]is a one-character string. bytes.hex()renders bytes as a hex string andbytes.fromhex()parses one back (it ignores whitespace) — the stdlib way to display or read hex dumps.- Other encodings exist —
latin-1,utf-16,ascii,cp1252— and you'll meet them in legacy files.stritself is encoding-agnostic; it only becomes bytes when youencode().
4.3 UnicodeDecodeError and errors=#
If bytes aren't valid in the encoding you claim, decode raises UnicodeDecodeError:
bad = b"caf\xe9" # a latin-1 é byte, invalid UTF-8
try:
bad.decode("utf-8")
except UnicodeDecodeError as e:
print("decode ->", type(e).__name__, ":", e)
print("errors='replace':", bad.decode("utf-8", errors="replace"))
print("errors='ignore':", bad.decode("utf-8", errors="ignore"))
print("errors='backslashreplace':", bad.decode("utf-8", errors="backslashreplace"))
print("as latin-1: ", bad.decode("latin-1"))decode -> UnicodeDecodeError : 'utf-8' codec can't decode byte 0xe9 in position 3: unexpected end of data
errors='replace': caf�
errors='ignore': caf
errors='backslashreplace': caf\xe9
as latin-1: caféThe errors= parameter controls recovery: "strict" (default, raise), "replace" (substitute �), "ignore" (drop), "backslashreplace" (show \xe9). In production, decode strictly first — silently replacing or ignoring corrupts data — and only fall back to a lenient mode when you know the source is dirty and you've logged it. This is exactly what 12.5 §2.1 does: "decode strictly; reject on UnicodeDecodeError; normalise to NFC".
The mirror image exists on the encode side: str.encode raises UnicodeEncodeError when a character has no representation in the target encoding — "café".encode("ascii"), or writing café to a console configured for cp1252. The same errors= escape hatches apply, with replace substituting ?:
try:
"café".encode("ascii")
except UnicodeEncodeError as e:
print("encode ->", type(e).__name__, ":", e)
print("errors='replace':", "café".encode("ascii", errors="replace"))
print("errors='backslashreplace':", "café".encode("ascii", errors="backslashreplace"))
print("errors='xmlcharrefreplace':", "café".encode("ascii", errors="xmlcharrefreplace"))encode -> UnicodeEncodeError : 'ascii' codec can't encode character '\xe9' in position 3: ordinal not in range(128)
errors='replace': b'caf?'
errors='backslashreplace': b'caf\\xe9'
errors='xmlcharrefreplace': b'café'xmlcharrefreplace (é → é) is the HTML/XML-safe variant; namereplace produces \N{LATIN SMALL LETTER E WITH ACUTE}. As with decoding, prefer strict first and lenient modes only for known-dirty output.
4.4 Normalization: NFC, NFD and friends#
Unicode has two ways to write the same visible character. é can be:
- NFC (composed): one code point
U+00E9—é - NFD (decomposed):
e+ combining acute accentU+0301—e+́(looks identical)
import unicodedata
composed = "café" # é as ONE code point
decomposed = unicodedata.normalize("NFD", composed)
print("composed :", composed, "| code points:", len(composed))
print("decomposed :", decomposed, "| code points:", len(decomposed))
print("equal as strings?", composed == decomposed)
print("NFC(decomposed) == composed?", unicodedata.normalize("NFC", decomposed) == composed)
print("composed bytes: ", composed.encode("utf-8"))
print("decomposed bytes:", decomposed.encode("utf-8"))composed : café | code points: 4
decomposed : café | code points: 5
equal as strings? False
NFC(decomposed) == composed? True
composed bytes: b'caf\xc3\xa9'
decomposed bytes: b'cafe\xcc\x81'The strings look identical but are not equal — different code points, different bytes, different len. (The decomposed line above renders café identically — it is e + combining acute U+0301; compare the code-point counts and bytes, not the glyphs.) This is the #1 cause of "why doesn't my search find it?" and "why did the dedup miss a duplicate?" bugs. The fix is always the same: normalise before comparing or storing:
for form in ["NFC", "NFD", "NFKC", "NFKD"]:
out = unicodedata.normalize(form, "① Hello-WORLD")
print(f"{form}: {out!r}")NFC: '① Hello-WORLD'
NFD: '① Hello-WORLD'
NFKC: '1 Hello-WORLD'
NFKD: '1 Hello-WORLD'- NFC composes (canonical equivalence) — the usual choice for storage and comparison.
- NFD decomposes — historically what macOS's HFS+ filesystem stored for file names, and what some input methods produce; so file names copied from a Mac can arrive decomposed.
- NFKC/NFKD additionally fold compatibility characters:
①→1, fullwidth-→-, ligaturefi→fi, superscripts→digits. Use NFKC when you want aggressive canonicalisation for matching; it can change meaning, so don't store NFKC text as your canonical form.
4.5 Case folding#
str.lower() and str.upper() are locale-insensitive but not fully case-folded. str.casefold() is the aggressive version designed for caseless matching:
print("'Straße'.casefold():", "Straße".casefold())
print("'STRASSE' == 'Straße'?", "STRASSE" == "Straße")
print("casefold compare:", "STRASSE".casefold() == "Straße".casefold())
print("'İ'.casefold():", "İ".casefold(), "-> len:", len("İ".casefold()))'Straße'.casefold(): strasse
'STRASSE' == 'Straße'? False
casefold compare: True
'İ'.casefold(): i̇ -> len: 2ß (German sharp s) lowercases to itself but casefolds to ss, so "STRASSE" and "Straße" match only under casefold. The Turkish capital dotted İ (U+0130) casefolds to i + a combining dot above (2 code points), so even case-insensitive matching can change a string's length. For user-input matching, dedup keys and search, casefold() is the right default — it's what Unicode recommends for caseless comparison.
4.6 Emoji, combining characters and grapheme clusters#
len() counts code points, not what a human sees as "one character". A flag emoji is two code points; a family emoji is seven; a woman technologist emoji is four:
flag = "🇮🇳"
print("len('🇮🇳'):", len(flag), "<- code points, not 1 visible char")
print("code points:", [hex(ord(c)) for c in flag])
print("utf-8 bytes:", len(flag.encode("utf-8")))
family = "👨👩👧👦"
print("len(family):", len(family), "code points (has ZWJ):",
[hex(ord(c)) for c in family])
e = "cafe\u0301" # e + combining acute = looks like café
print("'cafe'+combining acute len:", len(e), "vs NFC café len:", len("café"))
print("equal after NFC?", unicodedata.normalize("NFC", e) == "café")
print("'👩🏽💻' len:", len("👩🏽💻"))len('🇮🇳'): 2 <- code points, not 1 visible char
code points: ['0x1f1ee', '0x1f1f3']
utf-8 bytes: 8
len(family): 7 code points (has ZWJ): ['0x1f468', '0x200d', '0x1f469', '0x200d', '0x1f467', '0x200d', '0x1f466']
'cafe'+combining acute len: 5 vs NFC café len: 4
equal after NFC? True
'👩🏽💻' len: 4🇮🇳is two regional indicator code points (U+1F1EE,U+1F1F3) that render as one flag.👨👩👧👦is four people joined by three ZWJ (zero-width joiner,U+200D) code points — 7 code points, 1 visible emoji.cafe\u0301ise+ a combining accent that renders asé— 5 code points vs NFC's 4.👩🏽💻is woman + skin-tone modifier + ZWJ + laptop — 4 code points.
4.7 len() counts characters, not tokens#
len(text) gives you Unicode code points — not bytes, not words, and critically not tokens. The number that determines an LLM's context window and bill is the token count, which only the model's own tokenizer can produce:
texts = [
"Hello world",
"café — naïve résumé",
"こんにちは",
"This is a somewhat longer sentence with several words in it.",
]
for t in texts:
print(repr(t))
print(f" len() chars : {len(t)}")
print(f" utf-8 bytes : {len(t.encode('utf-8'))}")
print(f" .split() : {len(t.split())} (whitespace 'words')")'Hello world'
len() chars : 11
utf-8 bytes : 11
.split() : 2 (whitespace 'words')
'café — naïve résumé'
len() chars : 19
utf-8 bytes : 25
.split() : 4 (whitespace 'words')
'こんにちは'
len() chars : 5
utf-8 bytes : 15
.split() : 1 (whitespace 'words')
'This is a somewhat longer sentence with several words in it.'
len() chars : 60
utf-8 bytes : 60
.split() : 11 (whitespace 'words')Characters, bytes and "words" are all different counts — and none of them is the token count. こんにちは is 5 characters and 15 bytes, but its token count depends entirely on the tokenizer — it can be fewer or more than 5, and non-English text usually costs noticeably more tokens per character than English does. English averages roughly 4 characters per token, but that varies wildly too. This is why 02.2 exists: it teaches you to count tokens with the provider's tokenizer (tiktoken, transformers), and 02.7 §2.2 gives the "a million tokens ≈ 4 MB of English text" intuition. 05.6 §2.2 shows chunking by tokens, not characters.
4.8 BOMs and line endings#
Two file-format gremlins:
- BOM (byte-order mark):
utf-8-sigencoding writes a 3-byte signature (\xef\xbb\xbf) at the start of a file so some Windows tools know it's UTF-8. If you decode a BOM'd file as plainutf-8, the BOM becomes an invisible\ufeffcharacter at the start of your string — which breaksstartswith,==, regex^anchors and JSON parsing. Decode withutf-8-sigto strip it, or write files without a BOM (the modern default). - Line endings: Windows uses
\r\n(CRLF), macOS/Linux use\n(LF), old Mac used\r.splitlines()handles all three;split("\n")leaves\rat the end of each line on Windows files. When writing files,open(..., newline="")and explicit\nis the portable habit (01A.9 covers it).
text = "name,age\nAda,36"
print("LF bytes:", text.encode("utf-8"))
print("CRLF bytes:", text.replace("\n", "\r\n").encode("utf-8"))
bom = b"\xef\xbb\xbf" + text.encode("utf-8")
print("utf-8-sig strips BOM:", bom.decode("utf-8-sig"))
print("plain utf-8 keeps BOM as:", repr(bom.decode("utf-8")[:1]))LF bytes: b'name,age\nAda,36'
CRLF bytes: b'name,age\r\nAda,36'
utf-8-sig strips BOM: name,age
Ada,36
plain utf-8 keeps BOM as: '\ufeff'Part 5: Regular expressions#
Deep-dive
A regular expression (regex) is a pattern language for matching text: "find every occurrence of this shape". Python's re module is the standard tool, and you'll use it for log parsing, validation, extraction and cleaning. It's also the tool most likely to hurt you — catastrophic backtracking and "works on my test" failures are legendary. Learn the core functions, the pattern syntax, and the limits.
5.1 re in one page#
Seven functions cover 95% of use:
import re
text = "Tickets TKT-1041 and TKT-1042 were closed on 2026-11-05."
print("search:", re.search(r"TKT-\d+", text).group())
print("findall:", re.findall(r"TKT-\d+", text))
print("finditer:", [(m.group(), m.start()) for m in re.finditer(r"TKT-\d+", text)])
print("sub:", re.sub(r"\d+", "NNN", text))
print("split:", re.split(r"\s+and\s+", text))
print("match:", re.match(r"Tickets", text))
print("match mid-string:", re.match(r"TKT", text))
print("fullmatch:", re.fullmatch(r"TKT-\d+", "TKT-1042"))search: TKT-1041
findall: ['TKT-1041', 'TKT-1042']
finditer: [('TKT-1041', 8), ('TKT-1042', 21)]
sub: Tickets TKT-NNN and TKT-NNN were closed on NNN-NNN-NNN.
split: ['Tickets TKT-1041', 'TKT-1042 were closed on 2026-11-05.']
match: <re.Match object; span=(0, 7), match='Tickets'>
match mid-string: None
fullmatch: <re.Match object; span=(0, 8), match='TKT-1042'>searchfinds the first match anywhere;matchanchors at the start of the string;fullmatchrequires the whole string to match.findallreturns all matches as strings (or tuples when groups are present);finditerreturns match objects with.start()/.end()/.group().sub(pattern, repl, string)replaces matches;re.splitsplits on matches.re.compile(pattern, flags)pre-compiles for reuse — do it when the same pattern runs in a loop or across requests.
pat = re.compile(r"TKT-(?P<num>\d+)", re.IGNORECASE)
m = pat.search("ref tkt-0099 here")
print("compiled:", m.group(), "| named:", m.group("num"), "| span:", m.span())compiled: tkt-0099 | named: 0099 | span: (4, 12)5.2 Pattern syntax: classes, quantifiers, anchors, groups#
The pattern is a mini-language. The pieces you'll use daily:
| Syntax | Meaning | Example |
|---|---|---|
\d \w \s |
digit / word char / whitespace | \d+ one or more digits |
\D \W \S |
the negations | \S+ non-whitespace run |
. |
any char except newline | .* rest of line |
[...] |
character class | [A-Z], [aeiou], [^0-9] |
* + ? |
0+ / 1+ / 0-or-1 | colou?r |
{m,n} |
repeat count | \d{4}, \d{2,4} |
^ $ |
start / end of string (or line with MULTILINE) | ^ERROR |
(...) |
capturing group | (\d+)-(\d+) |
(?:...) |
non-capturing group | (?:ab)+ |
(?P<name>...) |
named group | (?P<year>\d{4}) |
| |
alternation | cat|dog |
\b |
word boundary | \bcat\b |
(?=...) (?!...) |
lookahead: zero-width assert on what follows | \d+(?=px) |
(?<=...) (?<!...) |
lookbehind: zero-width assert on what precedes | (?<=\$)\d+ |
m = re.search(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})", "closed on 2026-11-05.")
print("named groups:", m.groupdict())
m2 = re.search(r"(\d{4})-(\d{2})-(\d{2})", "2026-11-05")
print("groups:", m2.groups(), "| group(2):", m2.group(2))named groups: {'year': '2026', 'month': '11', 'day': '05'}
groups: ('2026', '11', '05') | group(2): 11Flags modify matching: re.IGNORECASE (case-insensitive), re.MULTILINE (^/$ match line boundaries), re.DOTALL (. matches newline), re.VERBOSE (ignore whitespace/comments in pattern):
text = "ERROR\nwarn\nERROR again"
print("no flag:", re.findall(r"^ERROR", text))
print("MULTILINE:", re.findall(r"^ERROR", text, re.MULTILINE))
print("IGNORECASE:", re.findall(r"error", "ERROR error Error", re.IGNORECASE))
print("DOTALL:", bool(re.search(r"a.b", "a\nb", re.DOTALL)),
"| without:", bool(re.search(r"a.b", "a\nb")))no flag: ['ERROR']
MULTILINE: ['ERROR', 'ERROR']
IGNORECASE: ['ERROR', 'error', 'Error']
DOTALL: True | without: FalseRewriting with re.sub. The replacement can reuse what the pattern captured — \1, \2 (or \g<name> for named groups) — or be a function that receives each match object and returns the new text. And re.VERBOSE lets a long pattern carry line breaks and comments, so it can be read like code:
import re
text = "Paid 12 invoices on 2026-11-05 and 3 refunds on 2026-11-06."
# 1. Backreferences in the replacement: reorder ISO dates into DD/MM/YYYY
print(re.sub(r"(\d{4})-(\d{2})-(\d{2})", r"\3/\2/\1", text))
# 2. Named groups work in the replacement too, as \g<name>
print(re.sub(r"(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})", r"\g<d>.\g<m>.\g<y>", "2026-11-05"))
# 3. A function as the replacement: called once per match, returns the new text
print(re.sub(r"\d+", lambda m: str(int(m.group()) * 2), "3 tickets, 12 notes"))
# 4. re.VERBOSE lets a long pattern carry whitespace and comments
ISO_DATE = re.compile(
r"""
(?P<year>\d{4}) - # four-digit year
(?P<month>\d{2}) - # two-digit month
(?P<day>\d{2}) # two-digit day
""",
re.VERBOSE,
)
print(ISO_DATE.search(text).groupdict())Paid 12 invoices on 05/11/2026 and 3 refunds on 06/11/2026.
05.11.2026
6 tickets, 24 notes
{'year': '2026', 'month': '11', 'day': '05'}In re.VERBOSE mode whitespace in the pattern is ignored, so to match a literal space or # you must escape it (\ or \#) or put it in a character class ([ ]).
Two more constructs you'll meet in the wild: lookaround assertions — (?=...)/(?!...) (lookahead) and (?<=...)/(?<!...) (lookbehind) — check context without consuming characters, so (?<=\$)\d+ finds digits only when preceded by $. They are zero-width, which makes them powerful and easy to get subtly wrong; Python's re requires lookbehinds to be fixed-width (the third-party regex module relaxes this). Most extraction is clearer with capture groups and partition — reach for lookarounds only when those can't express the match.
5.3 Greedy vs lazy, and catastrophic backtracking#
Quantifiers are greedy by default — .* eats as much as possible, then backtracks until the rest of the pattern matches. Add ? to make them lazy (non-greedy): match as little as possible:
s = "<b>bold</b> and <i>ital</i>"
print("greedy:", re.findall(r"<.*>", s))
print("lazy: ", re.findall(r"<.*?>", s))greedy: ['<b>bold</b> and <i>ital</i>']
lazy: ['<b>', '</b>', '<i>', '</i>']The greedy <.*> swallowed from the first < to the last >; lazy <.*?> stopped at the first >. Default to lazy when extracting between delimiters — it's almost always what you meant.
Catastrophic backtracking (ReDoS): nested quantifiers like (a+)+ or (a|a)* can make the regex engine try exponentially many partitions of the input. On adversarial input — a string of as followed by a non-matching char — it hangs:
import re, signal, time
def handler(signum, frame):
raise TimeoutError("regex took >5s")
signal.signal(signal.SIGALRM, handler)
pat = re.compile(r"(a+)+$")
for n in [10, 16, 20, 22]:
s = "a" * n + "!"
signal.alarm(5)
t0 = time.perf_counter()
try:
m = pat.search(s)
print(f"n={n}: no match, took {time.perf_counter() - t0:.4f}s")
except TimeoutError:
print(f"n={n}: TIMED OUT (>5s)")
break
finally:
signal.alarm(0)n=10: no match, took 0.0002s
n=16: no match, took 0.0080s
n=20: no match, took 0.1402s
n=22: no match, took 0.6275s(This demo is Unix/macOS-only — signal.SIGALRM doesn't exist on Windows; the point it makes is platform-independent.)
The times grow roughly 4× per +2 characters — exponential, about ×2 per extra character. n=30 would take minutes, n=40 days, n=50 years — effectively forever for anything serving requests. The safe rewrite a+$ is linear:
pat2 = re.compile(r"a+$")
for n in [10, 20, 30, 100]:
t0 = time.perf_counter()
pat2.search("a" * n + "!")
print(f"n={n}: {time.perf_counter() - t0:.6f}s")n=10: 0.000254s
n=20: 0.000006s
n=30: 0.000007s
n=100: 0.000056s5.4 When not to use a regex#
Regex matches patterns, not structure. It fails the moment the text has nesting or context-sensitivity:
| Don't use regex for... | Use instead |
|---|---|
| HTML / XML | html.parser, xml.etree, BeautifulSoup (third-party) |
| JSON | json.loads — never regex JSON |
Nested brackets ((())) |
a real parser |
| "Validate an email" | a pragmatic pattern + confirmation email, not a perfect regex |
| Code | a parser/AST |
The rule: regex for flat, local patterns; parsers for structure. If your pattern needs two levels of nesting or "match balanced X", stop and use a parser.
5.5 Ten practical patterns#
Patterns you'll actually write, with the Python to run them:
import re
PATTERNS = {
"email (loose)": r"[\w.+-]+@[\w-]+\.[\w.]+",
"ISO date": r"\d{4}-\d{2}-\d{2}",
"ticket id": r"TKT-\d{4,}",
"URL": r"https?://[^\s\"'<>]+",
"IPv4": r"\b(?:\d{1,3}\.){3}\d{1,3}\b",
"hex colour": r"#[0-9a-fA-F]{6}\b",
"money": r"\$\d+(?:\.\d{2})?",
"phone (loose)": r"\+?\(?\d[\d\s().-]{7,}\d",
"word": r"\b[\w']+\b",
"key=value": r"([^\s=]+)=([^\s]+)",
}
sample = ("Contact ada@example.com or visit https://ex.com/a?b=1. "
"Ticket TKT-1042, invoice $74.14, call +1 (555) 123-4567. "
"IP 192.168.1.1, colour #ff8800, date 2026-11-05.")
for name, pat in PATTERNS.items():
print(f"{name:22} {re.findall(pat, sample)}")email (loose) ['ada@example.com']
ISO date ['2026-11-05']
ticket id ['TKT-1042']
URL ['https://ex.com/a?b=1.']
IPv4 ['192.168.1.1']
hex colour ['#ff8800']
money ['$74.14']
phone (loose) ['+1 (555) 123-4567', '192.168.1.1', '2026-11-05']
word ['Contact', 'ada', 'example', 'com', 'or', 'visit', 'https', 'ex', 'com', 'a', 'b', '1', 'Ticket', 'TKT', '1042', 'invoice', '74', '14', 'call', '1', '555', '123', '4567', 'IP', '192', '168', '1', '1', 'colour', 'ff8800', 'date', '2026', '11', '05']
key=value [('https://ex.com/a?b', '1.')]For extraction that feeds structured output (03.4), prefer pulling the whole JSON-ish blob — either a fenced code block (match the triple-backtick fence with \x60{3} in the pattern, then (?:json)?\s*(\{.*?\})\s*\x60{3} — add re.DOTALL, or use [\s\S] for ., when the JSON spans multiple lines since . doesn't match \n) or a bare r"\{.*\}" with re.DOTALL — then json.loads it. Don't try to regex the fields inside.
re.escape(text) escapes a literal string for use in a pattern — use it whenever the pattern contains user data:
name = "file(1).txt"
print("pattern:", re.escape(name))
print("findall:", re.findall(re.escape(name), f"see {name} and {name} again"))pattern: file\(1\)\.txt
findall: ['file(1).txt', 'file(1).txt']Part 6: Text processing recipes#
Deep-dive
The patterns below are the ones you'll reuse in every data-cleaning, parsing and reporting task. Each is stdlib-only and deterministic.
6.1 Counting words and cleaning whitespace#
" ".join(text.split()) is the canonical whitespace collapse — it splits on any whitespace run and rejoins with single spaces, handling spaces, tabs, newlines and stray \r in one move:
raw = " Hello\t\tWorld \n\n Next line "
print("repr raw:", repr(raw))
print("split/join:", " ".join(raw.split()))repr raw: ' Hello\t\tWorld \n\n Next line '
split/join: Hello World Next lineFor word counts that ignore punctuation, re.findall(r"[a-zA-Z']+", text.lower()) beats split() because "dog." becomes "dog". For frequency counts, a plain dict is all you need at this stage (collections.Counter is the polished version — lesson 01A.4):
import re
text = "The quick brown fox jumps over the lazy dog. The dog barks."
words = re.findall(r"[a-zA-Z']+", text.lower())
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
print("total words:", len(words))
print("top 3:", sorted(counts.items(), key=lambda kv: -kv[1])[:3])total words: 12
top 3: [('the', 3), ('dog', 2), ('quick', 1)](Ties keep first-seen order because sorted is stable — which is why quick beat brown, fox and the rest at count 1. For a reproducible real top-N, sort by (-count, word).)
6.2 Slugifying#
A slug is URL-safe text: lowercase, ASCII, words joined by hyphens. The recipe: NFKD-normalise to split accented letters into base + combining mark, drop non-ASCII, replace non-word runs with -:
import re, unicodedata
def slugify(text: str) -> str:
text = unicodedata.normalize("NFKD", text)
text = text.encode("ascii", "ignore").decode("ascii")
text = re.sub(r"[^\w\s-]", "", text.lower())
return re.sub(r"[\s_]+", "-", text).strip("-")
for t in ["Hello World!", "Café naïve résumé", " --Weird__Title-- ", "Déjà Vu: 2026"]:
print(f"{t!r:30} -> {slugify(t)!r}")'Hello World!' -> 'hello-world'
'Café naïve résumé' -> 'cafe-naive-resume'
' --Weird__Title-- ' -> 'weird-title'
'Déjà Vu: 2026' -> 'deja-vu-2026'encode("ascii", "ignore") after NFKD is the trick that turns é→e, ü→u — combining marks get dropped because they're non-ASCII. For non-Latin scripts (Chinese, Arabic) this produces an empty slug — real systems keep the original or use a transliteration library.
6.3 Extracting fields from log lines#
Structured logs have a fixed shape; a named-group regex turns a line into a dict in one step:
import re
log = "2026-11-06 14:23:01 ERROR node-3 disk usage 97% on /var"
m = re.match(
r"(?P<date>\d{4}-\d{2}-\d{2}) (?P<time>\d{2}:\d{2}:\d{2}) "
r"(?P<level>\w+) (?P<host>[\w-]+) (?P<msg>.*)",
log,
)
print(m.groupdict()){'date': '2026-11-06', 'time': '14:23:01', 'level': 'ERROR', 'host': 'node-3', 'msg': 'disk usage 97% on /var'}re.match + ^-free pattern anchors at the start; (?P<name>...) gives you m.groupdict(). For log files that mostly match, use re.finditer over the file and collect the dicts — but always handle None (the non-matching lines) rather than assuming every line parses.
6.4 string.Template: simple templating#
For "fill in the blanks" text — email bodies, prompts, report headers — string.Template is safer than f-strings when the template comes from a file or user and the values are data:
import string
tmpl = string.Template("Dear $name, your ticket $ticket_id is $status.")
print(tmpl.substitute(name="Ada", ticket_id="TKT-1042", status="resolved"))
safe = string.Template("Dear $name, balance: $$ $amount")
print(safe.substitute(name="Bob", amount="42.00"))Dear Ada, your ticket TKT-1042 is resolved.
Dear Bob, balance: $ 42.00$name is a placeholder; $$ escapes a literal dollar. substitute raises KeyError/ValueError on missing or malformed placeholders — safe_substitute leaves them in place instead. For real prompt templating with conditionals and loops, Module 04's 04.10 covers Jinja2; string.Template is the stdlib floor.
6.5 difflib: comparing texts#
difflib.SequenceMatcher tells you how similar two strings are and where they differ — useful for "did the model change this text?" checks and duplicate detection:
import difflib
a = "the quick brown fox jumps over the lazy dog"
b = "the quick brown fox jumped over a lazy dog"
sm = difflib.SequenceMatcher(None, a, b)
for tag, i1, i2, j1, j2 in sm.get_opcodes():
print(f"{tag:8} a[{i1}:{i2}]={a[i1:i2]!r:12} b[{j1}:{j2}]={b[j1:j2]!r}")
print("ratio:", round(sm.ratio(), 3))equal a[0:24]='the quick brown fox jump' b[0:24]='the quick brown fox jump'
replace a[24:25]='s' b[24:26]='ed'
equal a[25:31]=' over ' b[26:32]=' over '
replace a[31:34]='the' b[32:33]='a'
equal a[34:43]=' lazy dog' b[33:42]=' lazy dog'
ratio: 0.918ratio() is 0.0–1.0 (1.0 = identical). get_opcodes() gives you the edit script: equal, replace, delete, insert blocks with indices into both strings. unified_diff/ndiff render the same info as readable diffs. For near-duplicate detection at scale, Module 05's 05.5 §6.3 covers MinHash/LSH — difflib is the exact-but-slow baseline.
6.6 Performance: why join beats repeated concatenation#
Building a string by s += piece in a loop can be O(n²): each + may copy the whole accumulated string. "".join(pieces) allocates once and is the idiomatic fast path:
import timeit
n = 20000
stmts = [
("A: s += piece", "s = ''\nfor i in range(%d):\n s += 'x' * 10\nlen(s)\n" % n),
("B: s = s + piece", "def build():\n s = ''\n for i in range(%d):\n"
" keep = s\n s = s + 'x' * 10\n return len(s)\n"
"build()\n" % n),
("C: ''.join(generator)", "len(''.join('x' * 10 for _ in range(%d)))\n" % n),
("D: ''.join(list)", "len(''.join(['x' * 10] * %d))\n" % n),
]
for name, stmt in stmts:
t = min(timeit.repeat(stmt, number=1, repeat=3))
print(f"{name:24} {t:8.4f} s")A: s += piece 0.0011 s
B: s = s + piece 0.0649 s
C: ''.join(generator) 0.0008 s
D: ''.join(list) 0.0002 sVariant A is deceptively fast because CPython — the standard Python implementation — has an in-place optimisation when the string has a single reference; variant B (which defeats it) shows the real quadratic cost — ~60× slower. join wins outright. The rule: accumulate pieces in a list, join once at the end. For truly huge text, stream it — generators (01A.5) let join consume lazily without holding everything in memory.
Part 7: The ticket-triage text toolkit#
Deep-dive
Everything so far assembles into the module's running example: a support-ticket triage toolkit. This lesson contributes the text layer — parsing a raw ticket blob into fields, normalising its text, and routing it with a keyword matcher. Later lessons add structures (01A.4), control flow (01A.3) and files (01A.9).
7.1 The raw material#
A ticket arrives as a blob of text — a metadata header line, then labelled free-text lines, the way an email or web form produces it:
RAW_TICKET = """\
TKT-1042 | billing | high | 2026-11-05
Customer: Ada Lovelace <ada@example.com>
Subject: Invoice total wrong
Body: I was charged $74.14 but the invoice says $72.49.
The sales tax looks double-counted — please refund the difference.
"""7.2 Parsing a raw ticket#
The header line is fixed-shape — a regex with named groups is the right tool. The body lines are Label: value pairs plus free text — partition(":") and startswith handle them without regex:
import re
import unicodedata
_HEADER_RE = re.compile(
r"^(?P<ticket_id>TKT-\d+)\s*\|\s*(?P<category>[^|]+)\s*\|\s*"
r"(?P<priority>[^|]+)\s*\|\s*(?P<date>\d{4}-\d{2}-\d{2})\s*$"
)
def parse_ticket(raw: str) -> dict:
"""Split a raw ticket blob into header fields plus body text."""
lines = raw.strip().splitlines()
header = _HEADER_RE.match(lines[0])
if header is None:
raise ValueError(f"bad ticket header: {lines[0]!r}")
ticket = {k: v.strip() for k, v in header.groupdict().items()}
body_lines = []
for line in lines[1:]:
if line.startswith("Body:"):
body_lines.append(line[len("Body:"):].strip())
elif line.startswith(("Subject:", "Customer:")):
key, _, value = line.partition(":")
ticket[key.strip().lower()] = value.strip()
else:
body_lines.append(line) # unlabelled line: the body continues
ticket["body"] = " ".join(body_lines).strip()
return ticket7.3 Normalizing and matching#
For matching, the text must be canonicalised first: NFC-normalise (so é forms agree), strip invisible format characters — Unicode general category Cf, which covers zero-width spaces, joiners and bidi controls (ZWJ U+200D is kept so emoji still compose) — casefold, collapse whitespace:
def normalize_text(text: str) -> str:
"""NFC-normalise, drop format chars (keep ZWJ), casefold, collapse space."""
text = unicodedata.normalize("NFC", text)
text = "".join(c for c in text
if unicodedata.category(c) != "Cf" or c == "\u200d")
return " ".join(text.casefold().split())
_KEYWORDS = {
"billing": ("invoice", "charge", "charged", "refund", "tax",
"payment", "price", "total"),
"bug": ("error", "crash", "broken", "fails", "exception",
"bug", "not working"),
"account": ("password", "login", "account", "email", "sign in"),
}
def keyword_route(text: str) -> str:
"""Route by counting keyword hits in the normalised text."""
norm = normalize_text(text)
scores = {route: sum(1 for kw in kws if kw in norm)
for route, kws in _KEYWORDS.items()}
best = max(scores, key=scores.get)
return best if scores[best] > 0 else "general"This is deliberately a keyword matcher — dumb, fast, inspectable. Its job is to be the baseline the smarter versions (a rules engine, then an LLM classifier in later modules) must beat. Note keyword_route is case-insensitive for free because normalize_text already casefolds. Substring matching has its own false positives — tax is found inside syntax, bug inside debug — and word-boundary patterns (re.search(r"\btax\b", norm)) are the first fix; later lessons replace the whole table with something smarter.
7.4 The assembled module#
Put it together in ticket_text.py and run it:
if __name__ == "__main__":
ticket = parse_ticket(RAW_TICKET)
for k, v in ticket.items():
print(f"{k:10} {v}")
print("-" * 50)
print("normalised body:", normalize_text(ticket["body"]))
print("route:", keyword_route(ticket["subject"] + " " + ticket["body"]))ticket_id TKT-1042
category billing
priority high
date 2026-11-05
customer Ada Lovelace <ada@example.com>
subject Invoice total wrong
body I was charged $74.14 but the invoice says $72.49. The sales tax looks double-counted — please refund the difference.
--------------------------------------------------
normalised body: i was charged $74.14 but the invoice says $72.49. the sales tax looks double-counted — please refund the difference.
route: billingEvery technique from this lesson is doing work here: regex header parsing, splitlines/startswith/partition for labelled fields, str.join for the body, unicodedata.normalize + casefold + whitespace collapse for matching, and an f-string for display. In 01A.9 this same module learns to read tickets from CSV/JSON files instead of a literal; in later modules the keyword_route baseline gets replaced by an LLM call — and the normalize_text step becomes the first stage of your ingestion pipeline (05.5).
Common mistakes#
The gallery — each snippet below is real, deterministic stdlib Python:
Float == comparison. 0.1 + 0.2 is a different float than 0.3, so == says False while math.isclose says True:
import math
print(0.1 + 0.2 == 0.3)
print(repr(0.1 + 0.2))
print(math.isclose(0.1 + 0.2, 0.3))False
0.30000000000000004
True§1.2 has the full story; for money use Decimal/Fraction (§1.6).
"Editing" an immutable string. str cannot be changed in place — every "edit" builds a new string:
s = "hello"
s[0] = "H"Traceback (most recent call last):
File "mm_immutable.py", line 2, in <module>
s[0] = "H"
~^^^
TypeError: 'str' object does not support item assignmentRebuild instead: "H" + s[1:], s.replace("h", "H", 1) or an f-string — see §2.2.
Slicing off-by-one. s[a:b] excludes b — "characters 8 through 13 inclusive" needs text[8:14], not text[8:13]:
text = "support ticket"
print(repr(text[8:13])) # wanted 'ticket' — got 'ticke'
print(repr(text[8:14])) # stop is exclusive
print(repr(text[-6:])) # same answer, negative-index shortcut'ticke'
'ticket'
'ticket'§2.3 has the rules; slices never raise IndexError on out-of-range, which is its own trap.
Decoding bytes as the wrong encoding. b"caf\xe9" is a Latin-1 é byte — invalid UTF-8 — so strict decode raises:
bad = b"caf\xe9" # a latin-1 é byte, invalid UTF-8
bad.decode("utf-8")Traceback (most recent call last):
File "mm_encoding.py", line 2, in <module>
bad.decode("utf-8")
~~~~~~~~~~^^^^^^^^^
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 3: unexpected end of dataDecode strictly first and only fall back to errors= modes on known-dirty input — §4.3. The mojibake café is the mirror image: UTF-8 bytes decoded as Latin-1.
Greedy regex swallowing too much. .* is greedy by default — it eats to the last >; add ? for lazy:
import re
s = "<b>bold</b> and <i>ital</i>"
print(re.findall(r"<.*>", s))
print(re.findall(r"<.*?>", s))['<b>bold</b> and <i>ital</i>']
['<b>', '</b>', '<i>', '</i>']Default to lazy when extracting between delimiters. The deadlier cousin is catastrophic backtracking — nested quantifiers like (a+)+ hang exponentially on adversarial input; §5.3 shows the timing curve and the defences.
Common misconceptions#
| Misconception | Reality |
|---|---|
"0.1 + 0.2 == 0.3 should be true." |
Floats are binary; 0.1 and 0.2 have no exact representation, so the sum is 0.30000000000000004. Use math.isclose or Decimal. |
| "Python ints overflow like C ints." | int is arbitrary precision — 10**100 works fine. |
"round() rounds half up." |
It rounds half to even (banker's rounding): round(2.5) == 2, round(3.5) == 4. For money, use Decimal with ROUND_HALF_UP. |
| "-7 % 2 is -1." | Python's % is a mathematical modulo with the divisor's sign: -7 % 2 == 1. |
| "Strings can be changed in place." | str is immutable; every "edit" makes a new string. Use bytearray for mutable bytes. |
"len(text) tells me the token count / cost." |
It counts code points. Tokens come from the model's tokenizer — see 02.2. |
| "`"café" == "café" is always True." | Only if both use the same normalisation form. NFC and NFD versions look identical but compare unequal. |
| "Regex can parse JSON/HTML." | It can't — those are nested structures. Use json.loads or an HTML parser. |
".* is greedy so it always grabs too much." |
Greedy is the default and often right for "rest of line"; use .*? (lazy) when extracting between delimiters. |
| "A regex that works on my tests is safe." | Nested quantifiers can backtrack exponentially on adversarial input (ReDoS). Keep patterns simple; cap input length. |
"str.lower() and casefold() are the same." |
casefold() is the aggressive caseless-match form (ß→ss); use it for comparisons. |
"+ and join are interchangeable." |
join is faster and idiomatic for many pieces; + is fine for a few. |
"s[100:] raises IndexError like s[100]." |
Slices never raise on out-of-range — they return "". Only single-index access raises. |
Key takeaways#
intis arbitrary precision;floatis IEEE-754 binary. Never compare floats with==— usemath.isclose.nanis never equal to anything, even itself.Decimalfor money,Fractionfor exact ratios,floatfor measurements. ConstructDecimalfrom strings, never floats.//floors,%is mathematical modulo (sign of the divisor),divmodreturns both.round()is banker's rounding.stris immutable — index, slice (s[a:b:c], negative indices,::2,::-1), and rebuild with methods.joinbeats+in loops.- The method working set:
strip/split/splitlines/rsplit,join,replace,startswith/endswith,find/index/count,partition/rpartition,lower/upper/title/capitalize/casefold,isdigit/isalpha/isalnum/isspace,zfill/ljust/rjustand "center" padding,removeprefix/removesuffix,translate/maketrans. - f-strings are the default for formatting; the
:specmini-language handles width, alignment, precision, separators, signs and types.str.format/%are legacy — recognise, don't write. stris characters;bytesis encoded data. UTF-8 is the standard.encode/decodewith explicitencoding="utf-8"; handleUnicodeDecodeErrorstrictly first.- Normalise before comparing: NFC for storage/comparison,
casefold()for matching.len()counts code points — not bytes, words, or tokens. recore functions:search,match,fullmatch,findall,finditer,sub,split;re.compilefor reuse. Greedy by default,?for lazy. Beware catastrophic backtracking on untrusted input.- Recipes:
" ".join(text.split())collapses whitespace; NFKD+ascii slugify; named-group regex for log fields;string.Templatefor fill-in text;difflibfor similarity.
Where you'll use this in the AI path#
| Skill from this lesson | Used in |
|---|---|
len(text) vs token count, characters vs bytes |
02.2 §1.2, 02.2 Part 9 (whitespace, case, numbers as tokens), 02.2 Part 8 |
| Counting tokens for billing/truncation | 02.2 §6, 02.7 §2.2, 05.6 §2.2 |
str.encode/bytes, base64 |
03.6 §1.3 (images/files in requests) |
| Unicode normalisation, invisible chars, casefold | 05.5 Part 2 (ingestion cleaning), 12.5 §2.1 (UnicodeGuard) |
| Whitespace collapsing, dedup, entity normalisation | 05.5 §3.1, 05.5 Part 7 |
| Regex extraction, JSON-from-text | 03.4 §1.2 (parse rung), 04.8 §8.5 |
string.Template, prompt assembly |
04.10 §2.3, 04.4 §2.7 |
| Streaming text assembly | 03.3 Part 5 |
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Arbitrary precision | int grows to any size; no overflow at 32/64 bits |
| IEEE 754 | The standard binary floating-point format float uses |
math.isclose |
Float comparison with tolerance, instead of == |
nan / inf |
Float values for "not a number" / infinity; nan != nan always |
| Floor division / modulo | // rounds down; % returns a result with the divisor's sign |
divmod |
Returns (a // b, a % b) as a tuple |
| Banker's rounding | round() rounds half to even, not half up |
Decimal |
Exact base-10 arithmetic for money; construct from strings |
Fraction |
Exact rational arithmetic (1/3 stays 1/3) |
bool is int |
True == 1, isinstance(True, int) is True |
| Immutable | A value that can't be changed in place; "edits" create new objects |
| Slice | s[start:stop:step] substring; stop is exclusive, negatives count from end |
| Raw string | r"..." keeps backslashes literal — for regex and paths |
str.join |
sep.join(list) builds a string; the fast idiom vs + in loops |
casefold |
Aggressive caseless mapping for comparison (ß→ss) |
| f-string | f"{expr:spec}" evaluates expressions inline; the modern format tool |
| Format spec | The :... mini-language: fill/align/sign/width/precision/type |
t-string / Template |
t"..." literal (3.14+) that keeps literal text and interpolated values separate in a string.templatelib.Template instead of joining them into a str |
repr vs str |
Developer-exact vs human-friendly text; repr quotes and escapes |
pprint |
Pretty-prints nested data structures readably |
| Code point | A character's Unicode number (U+00E9) |
| UTF-8 | The standard encoding: 1–4 bytes per code point |
bytes / bytearray |
Immutable / mutable raw byte sequences |
UnicodeDecodeError |
Raised when bytes aren't valid in the claimed encoding |
UnicodeEncodeError |
Raised when text can't be encoded into the target encoding; same errors= recovery modes |
errors= |
Decode/encode recovery mode: strict, replace, ignore, backslashreplace (+ xmlcharrefreplace, namereplace on encode) |
| Normalisation (NFC/NFD/NFKC/NFKD) | Canonical compose/decompose and compatibility folding of Unicode text |
| Grapheme cluster | What a human sees as one character; may be several code points |
| BOM | Byte-order mark; utf-8-sig strips it, plain utf-8 keeps \ufeff |
| Regular expression | Pattern language for matching text shapes |
| Greedy vs lazy | */+ match max then backtrack vs *?/+? match min |
| Catastrophic backtracking / ReDoS | Exponential regex blowup on adversarial input |
re.compile |
Pre-compiled pattern object for reuse |
| Lookaround | Zero-width regex assertions (?=...)/(?<=...) that check context without consuming characters |
| Slug | URL-safe lowercase-hyphenated text |
string.Template |
$name placeholder substitution for fill-in text |
difflib |
Sequence comparison: similarity ratio and edit opcodes |
All terms are also collected in the glossary.
Exercises#
Run the code from this lesson and experiment:
- Decimal invoice (1.6): price three items
("Widget","19.99","3"), ("Gadget","45.00","1"), ("Cable","7.50","2")withDecimal, add 8.25% tax rounded half-up to cents. What's the total? - Float equality (1.2):
total = 0.1 + 0.2. Showtotal == 0.3isFalseandmath.isclose(total, 0.3)isTrue. Then find a tolerance (rel_tol/abs_tol) that makesisclosework for comparing prices to the cent. - Pagination (1.3): 100 tickets, 7 per page. Use
divmodto get full pages and leftover tickets. - Rounding modes (1.4/1.6): compare
round(2.5),round(0.125, 2)withDecimalROUND_HALF_UP. When does each matter? - Domain extraction (2.3/2.5): from
"ada.lovelace@example.co.uk"extract the domain withrpartition, then the top-level domain (TLD). - join (2.4/6.6): build
"TKT-1042,billing,high,2026-11-05"from a list of fields withjoin, and the same with+. Why isjoinpreferred? - key=value pairs (2.5/6.4): parse
"user=bob;role=admin;team=platform"into a dict usingsplit+partition. - Table formatting (3.5): print a 2-column table (
ID,Amount) with dynamic width and.2famounts using nested format specs. - Unicode equality (4.4): show
"café"(NFC) != its NFD form as strings but equal afternormalize("NFC", ...). Compare their UTF-8 byte lengths. - Decode recovery (4.3): decode
b"caf\xe9s"as UTF-8 witherrors="replace"and aslatin-1. Which is "correct" depends on the source — explain. - findall (5.1/5.5): extract all emails from
"mail ada@x.com or bob.smith@corp.io, not an email @bad". - Log parsing (5.2/6.3): parse
"2026-11-06 14:23:01 WARN api latency 812ms"into a dict with named groups. - Greedy vs lazy (5.3): extract
(tag, content)pairs from"<b>bold</b> and <i>ital</i>"using a backreference pattern</\1>. - Slugify (6.2): slugify
"Hello, World! 2026"with the NFKD recipe. - Template + similarity (6.4/6.5): substitute
"Hi $name, you have $n tickets."withname="Ada", n=3; computedifflibratio of"the cat sat"vs"the cat sat down"; andFraction(1,3)+Fraction(1,6).
Solutions
1. Decimal invoice
from decimal import Decimal, ROUND_HALF_UP
items = [("Widget","19.99","3"), ("Gadget","45.00","1"), ("Cable","7.50","2")]
subtotal = sum(Decimal(p) * Decimal(q) for _, p, q in items)
tax = (subtotal * Decimal("0.0825")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
print("subtotal:", subtotal, "| tax:", tax, "| total:", subtotal + tax)subtotal: 119.97 | tax: 9.90 | total: 129.872. Float equality
import math
total = 0.1 + 0.2
print(total == 0.3, math.isclose(total, 0.3))
print(math.isclose(74.10, 74.10 + 1e-9, rel_tol=0, abs_tol=0.005))False True
TrueFor money, compare Decimal values or use abs_tol=0.005 (half a cent) — rel_tol alone is wrong for small amounts.
3. Pagination
pages, leftover = divmod(100, 7)
print("full pages:", pages, "| leftover:", leftover)full pages: 14 | leftover: 214 full pages of 7 = 98 tickets, 2 leftover on page 15.
4. Rounding modes
from decimal import Decimal, ROUND_HALF_UP
print(round(2.5), round(0.125, 2))
print(Decimal("2.5").quantize(Decimal("1"), rounding=ROUND_HALF_UP),
Decimal("0.125").quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))2 0.12
3 0.13round is banker's (2.5→2, 0.125→0.12); Decimal half-up gives 3 and 0.13 — what invoices and tax rules expect.
5. Domain extraction
email = "ada.lovelace@example.co.uk"
domain = email.rpartition("@")[2]
print(domain, domain.rpartition(".")[2])example.co.uk ukrpartition splits at the last @/., so multi-part top-level domains work.
6. join
fields = ["TKT-1042", "billing", "high", "2026-11-05"]
print(",".join(fields))TKT-1042,billing,high,2026-11-05join is one allocation vs +'s repeated copies; always prefer it for lists.
7. key=value pairs
pairs = "user=bob;role=admin;team=platform"
d = dict(p.partition("=")[::2] for p in pairs.split(";"))
print(d){'user': 'bob', 'role': 'admin', 'team': 'platform'}partition("=") returns (key, "=", value); [::2] keeps key and value.
8. Table formatting
wid = 10
print(f"{'ID':<{wid}}|{'Amount':>{wid}}")
for tid, amt in [("TKT-1", 74.1), ("TKT-2", 1200.5)]:
print(f"{tid:<{wid}}|{amt:>{wid}.2f}")ID | Amount
TKT-1 | 74.10
TKT-2 | 1200.50Nested specs {wid} inside {:<{wid}} make column widths dynamic.
9. Unicode equality
import unicodedata
a = "café"
b = unicodedata.normalize("NFD", a)
print(a == b, unicodedata.normalize("NFC", b) == a)
print(len(a.encode()), len(b.encode()))False True
5 6NFC é is 2 UTF-8 bytes; NFD e+combining acute is 3 — same glyph, different bytes.
10. Decode recovery
bad = b"caf\xe9s"
print(bad.decode("utf-8", errors="replace"))
print(bad.decode("latin-1"))caf�s
cafésreplace shows the corruption; latin-1 "works" only if the source really was Latin-1 — which is the mojibake trap.
11. findall emails
import re
text = "mail ada@x.com or bob.smith@corp.io, not an email @bad"
print(re.findall(r"[\w.+-]+@[\w-]+\.[\w.]+", text))['ada@x.com', 'bob.smith@corp.io']@bad has no domain dot so it's correctly skipped.
12. Log parsing
import re
log = "2026-11-06 14:23:01 WARN api latency 812ms"
m = re.match(r"(?P<d>\d{4}-\d{2}-\d{2}) (?P<t>\d{2}:\d{2}:\d{2}) (?P<lv>\w+) (?P<msg>.*)", log)
print(m.groupdict()){'d': '2026-11-06', 't': '14:23:01', 'lv': 'WARN', 'msg': 'api latency 812ms'}13. Greedy vs lazy
import re
s = "<b>bold</b> and <i>ital</i>"
print(re.findall(r"<(\w+)>(.*?)</\1>", s))[('b', 'bold'), ('i', 'ital')]The backreference \1 ensures the closing tag matches the opening one; .*? is lazy so it stops at the first </.
14. Slugify
import re, unicodedata
def slugify(t):
t = unicodedata.normalize("NFKD", t).encode("ascii","ignore").decode()
t = re.sub(r"[^\w\s-]","",t.lower())
return re.sub(r"[\s_]+","-",t).strip("-")
print(slugify("Hello, World! 2026"))hello-world-202615. Template + similarity
import string, difflib
from fractions import Fraction
print(string.Template("Hi $name, you have $n tickets.").substitute(name="Ada", n=3))
a, b = "the cat sat", "the cat sat down"
print("ratio:", round(difflib.SequenceMatcher(None, a, b).ratio(), 3))
print(Fraction(1,3) + Fraction(1,6))Hi Ada, you have 3 tickets.
ratio: 0.815
1/2Check yourself#
- Why is
0.1 + 0.2 != 0.3in Python, and what's the right way to compare floats?Floats are binary; 0.1 and 0.2 have no exact binary representation, so their sum is0.30000000000000004. Usemath.isclose(a, b)orDecimal. - What's the difference between
intandfloatin Python, and why doesn'tintoverflow?intis a whole number of arbitrary precision (no overflow);floatis a 64-bit IEEE-754 binary fraction.intdoesn't overflow because Python allocates as many digits as needed. - What does
-7 % 2evaluate to, and why might that surprise a JavaScript programmer?1— Python's%is mathematical modulo with the divisor's sign. JS's%is truncated (-7 % 2 === -1). - When should you use
Decimalinstead offloat? How do you construct aDecimalcorrectly?When exactness matters — money, tax, anything that must add to the cent. Construct from strings:Decimal("19.99"), neverDecimal(19.99). - What does
round(2.5)return, and how do you get "round half up" for money?2— banker's rounding (half to even). For half-up useDecimal.quantize(..., rounding=ROUND_HALF_UP). - Why is
s[0] = "H"an error on a string, and what's the idiomatic fix?Strings are immutable; you can't assign to an index. Fix withs.replace(...)or rebuild ("H" + s[1:]). - What's the difference between
s.find(x)ands.index(x)?findreturns-1on a miss;indexraisesValueError. Usefindwhen absence is normal,indexwhen it's a bug. - Why is
" ".join(parts)preferred overpartsconcatenated with+in a loop?joinallocates once;+in a loop can copy the whole accumulated string each iteration (quadratic). Accumulate in a list, join once. - For text comparison and matching, what do
casefold()and NFC/NFD normalisation each handle?casefold()is the aggressive caseless-match form — it mapsß→ssand similar special cases, so"STRASSE"matches"Straße". NFC composes (é= 1 code point) while NFD decomposes (e+ combining accent = 2 code points); they look identical but compare unequal, so normalise before comparing or storing. - In
f"{value:>10.2f}", what do>,10and.2feach control?>right-aligns,10is minimum width,.2fis float with 2 decimals. - What's the difference between
strandbytes, and when do you needencode/decode?stris Unicode text (characters);bytesis raw encoded data (1–4 bytes per char in UTF-8). Youencodetext→bytes for storage/transmission anddecodebytes→text on receipt. - Why does
len("🇮🇳")return 2, and what does that tell you aboutlen()?It's two regional-indicator code points that render as one flag.len()counts code points, not visible characters. - Name the core
refunctions and what each returns.search(first match anywhere),match(anchored at start),fullmatch(whole string),findall(all matches as strings),finditer(match objects with positions),sub(replace matches),split(split on matches). - What is catastrophic backtracking, what pattern shape triggers it, and how do you defend against it?Exponential backtracking when nested quantifiers like
(a+)+try every partition of input. Triggered by ambiguous nested quantifiers on non-matching input. Defend with simple patterns (no nested quantifiers over overlapping classes), input length caps, timeouts, or a parser. - When should you not use a regex, and what should you use instead?For nested/structured text: JSON (
json.loads), HTML/XML (a parser), balanced brackets, code. Regex is for flat, local patterns.
Further resources#
- Python docs: Numbers and Strings — the tutorial's concise coverage.
- Python docs: Numeric Types —
int,float,complexdetails, including theint↔floatconversion rules. - Python docs:
decimalandfractions— exact arithmetic. - Python docs: String Methods and Format Specification Mini-Language — the complete reference for
strmethods and f-string specs. - Python docs:
re— the regular-expression HOWTO andrereference, including the backtracking warning. - Python docs: Unicode HOWTO — the authoritative guide to
str/bytes/encodings. - Python docs:
unicodedata— normalisation and character properties. - Unicode glossary — code point, grapheme cluster, normalisation defined by the standards body.
- PEP 750 — Template Strings and
string.templatelib— the 3.14t"..."literal previewed in 3.6. - PEP 8 — the style guide this module follows.
← 01A.1 — Running Python: Programs, the REPL and Syntax Basics | Module 01A overview | 01A.3 — Control Flow and Functions →