Sub topic 13
Chaining Methods into a Cleanup Pipeline
This chapter assumes you know basic Python syntax, can read str literals and indexing, and have met the individual methods strip, split, join, replace, casefold, translate, partition, and startswith. Here you combine them. The aim is to build short pipelines that turn messy input into a predictable form, and to avoid the ordering mistakes that make chains return wrong results without raising an error.
Why chaining works
Every str method returns a new string and leaves the original unchanged. The return value is a str, so you can call another str method on it immediately. A chain is only a sequence of these calls, each one working on the output of the previous call.
raw = " Hello World "
clean = " ".join(raw.split()).lower()
print(clean) # hello world
print(repr(raw)) # ' Hello World 'Here raw.split() produces a list, " ".join(...) turns that list back into a string, and .lower() runs on that string. The original raw is untouched, because no step modified it.
Not every method returns a string. split, splitlines, and partition return a list or tuple, and find, count, and startswith return numbers or booleans. A chain breaks when you call a string method on one of those results. The pattern " ".join(...) is the usual way back from a list to a string.
# This fails: split() returns a list, and lists have no lower()
try:
"A B".split().lower()
except AttributeError as exc:
print(exc) # 'list' object has no attribute 'lower'The shape of a pipeline
A cleanup pipeline moves from coarse to fine. Most pipelines follow the same stages:
- Trim the outer edges of the string.
- Normalize case.
- Remove or replace unwanted characters.
- Collapse whitespace.
- Split, validate, or rebuild the result.
Not every pipeline needs every stage. The stages show where each kind of step usually belongs, so that the order stays predictable.
A worked example: building a slug
A slug is a lowercase, hyphen-separated piece of text for URLs and filenames. This function applies the stages in order.
def slugify(title: str) -> str:
cleaned = title.strip().casefold()
delete_punctuation = str.maketrans("", "", "'\"!?.,")
cleaned = cleaned.translate(delete_punctuation)
return "-".join(cleaned.split())
print(slugify(" Hello, World! It's Python? "))
# hello-world-its-pythonThe steps run like this:
stripremoves the outer spaces.casefoldmakes the text lowercase for comparison.translatedeletes the listed punctuation in a single pass.split()with no arguments breaks the text on any run of whitespace and drops empty fields."-".join(...)rebuilds the string with single hyphens.
The split() and join pair is the standard way to collapse repeated whitespace. A chain of replace(" ", " ") calls would leave some double spaces when the input contains three or more in a row.
Formatting a long chain
When a chain is longer than about three calls, wrap it in parentheses and put one method on each line. Python allows line breaks inside parentheses, so no backslashes are needed.
def normalize_tag(raw: str) -> str:
return (
raw.strip()
.casefold()
.replace("_", " ")
.replace("-", " ")
.removeprefix("#")
)
print(normalize_tag(" #Machine_Learning-Basics "))
# machine learning basicsCheck this output carefully. After strip and casefold the text is #machine_learning-basics. The two replace calls change the underscore and hyphen to spaces. Then removeprefix("#") removes the leading #. The result has no stray characters, and each line states one transformation, so you can read the function from top to bottom.
Order matters
The same methods in a different order can give different results. Most ordering errors fall into three groups.
Trim before you test the ends
removesuffix, removeprefix, startswith, and endswith look at the exact ends of the string. Trailing whitespace or a newline makes them fail silently.
line = "report.csv\n"
print(repr(line.removesuffix(".csv"))) # 'report.csv\n'
print(repr(line.strip().removesuffix(".csv"))) # 'report'The first call does nothing, because the string ends with \n, not with .csv. No exception is raised, so the bug is easy to miss. Strip first.
Fold case before you match
If you replace or test text that has mixed case, fold the case first, or the pattern must cover every case variant.
title = "Report FINAL Draft"
print(title.replace("final", "").split())
# ['Report', 'FINAL', 'Draft'] (nothing was replaced)
print(title.casefold().replace("final", "").split())
# ['report', 'draft']The cost of folding first is that the output is also folded. If you need to keep the original case, search with a folded copy and edit the original by position. That is more work, and it is a sign that the task may belong to re (see the last section).
Pick the right trimming tool
strip, lstrip, and rstrip treat their argument as a set of characters. removeprefix and removesuffix treat it as one exact piece of text.
print("web.com".lstrip("www.")) # eb.com
print("web.com".removeprefix("www.")) # web.comlstrip("www.") removes any leading w or . characters, and so it also eats the w in web. If you mean "remove this exact text if it is there," use removeprefix or removesuffix.
Debugging a chain
A chain hides its intermediate values. To see them, write the steps as a list of functions and run them in a loop. This also lets you reuse and reorder steps.
def run_pipeline(text, steps, trace=False):
for step in steps:
text = step(text)
if trace:
print(f"{step.__name__:>12}: {text!r}")
return text
def collapse_spaces(s):
return " ".join(s.split())
steps = [str.strip, str.casefold, collapse_spaces]
result = run_pipeline(" Tab\tSeparated TEXT \n", steps, trace=True)
print(result)The output is:
strip: 'Tab\tSeparated TEXT'
casefold: 'tab\tseparated text'
collapse_spaces: 'tab separated text'
tab separated textThe tab character is not a space, so strip leaves the inner one alone. split() treats tabs and newlines as whitespace, which is why collapse_spaces turns the tab into a single space. Tracing exposes this kind of detail immediately. The {step.__name__:>12} format right-aligns the name in 12 characters, and a longer name such as collapse_spaces simply extends the field.
Pipelines over many lines
For multi-line text, apply a per-line pipeline inside a loop over splitlines(). This function parses simple key = value configuration text.
def parse_settings(text: str) -> dict[str, str]:
result = {}
for line in text.splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
key, sep, value = line.partition("=")
if not sep:
continue # no "=" on this line
result[key.strip().casefold()] = value.strip()
return result
config = """
Name = Ada Lovelace
ROLE= Analyst
# a comment
city = London = UK
"""
print(parse_settings(config))
# {'name': 'Ada Lovelace', 'role': 'Analyst', 'city': 'London = UK'}Several earlier ideas work together here:
splitlines()handles\n,\r\n, and other line endings, whichsplit("\n")does not.partition("=")splits once, so a value that contains=stays whole. It also returns an empty separator when=is missing, and theif not sepcheck uses that to skip the line.- Keys are trimmed and case-folded. Values are only trimmed, because their case may matter.
Not every field gets the same treatment. A pipeline should normalize only what you need to compare, and leave the other content as it was.
Handling None and non-strings
String methods fail on None and on numbers. Data from files, forms, and databases often contains missing values. Decide at the start of the pipeline what to do about them.
def clean_cell(value) -> str:
if value is None:
return ""
return " ".join(str(value).split())
print(repr(clean_cell(None))) # ''
print(repr(clean_cell(42))) # '42'
print(repr(clean_cell(" a b "))) # 'a b'Avoid the shortcut (value or ""), because it also turns 0 into an empty string. Test for None explicitly when zero is a valid value.
Cost and readability
Each step in a chain builds a new string, so a chain of five steps makes five intermediate strings. For normal text such as names, lines, and tags this cost is small. Do not merge steps to save time unless a profile shows that the pipeline is a bottleneck. A single translate call is the exception: it replaces many single-character replace calls and does the work in one pass.
When the chain gets too long
A chain of many replace calls, or a pipeline with conditions on the surrounding characters, is a signal to switch tools. You should consider the re module if you notice any of these:
- You need to match a pattern, such as "one or more digits" or "a word at a boundary," not a fixed piece of text.
- You need to replace text only in certain contexts, such as a whole word and not a substring.
- You must keep the original case while matching case-insensitively.
For fixed text, character sets, and whitespace, the string methods in a short chain are clearer and easier to test than a regular expression.
Exercise
The function below should return the name of a file without its extension, for any of the extensions ".csv" or ".tsv", ignoring case. It returns the wrong result for " Data.CSV\n". Describe what to change and why: def stem(name): return name.removesuffix(".csv").removesuffix(".tsv").strip().casefold()
Show answer
The strip and casefold calls run after the suffix removal, so the suffix test sees " Data.CSV\n", which ends with a newline and has uppercase letters. Both removesuffix calls change nothing. Move strip() and casefold() to the front of the chain: name.strip().casefold().removesuffix(".csv").removesuffix(".tsv"). The input then becomes "data.csv" before the suffix is tested, and the result is "data".
Exercise
Write a pipeline that turns " Ünïcode TEXT\there " into "ünïcode text here" using only str methods, and say which splitting call collapses the tab.
Show answer
Use " ".join(s.split()).casefold(). The call s.split() with no arguments splits on any run of whitespace, including spaces and tabs, and drops the empty fields at both ends, so strip is not needed. join rebuilds the text with single spaces, and casefold lowercases it. The result is "ünïcode text here".