Sub topic 13
Chaining methods into a cleanup pipeline
This chapter assumes you know that str methods return new strings, and that you have used strip, split, join, lower, and translate on their own. Here you combine them into short pipelines.
Why chaining works
Strings are immutable, so every method returns a new string. You can call another method directly on that result. Each call takes the output of the one before it:
raw = " Hello World "
clean = " ".join(raw.split()).lower()
print(clean) # hello worldRead the pipeline from the inside out. raw.split() returns ['Hello', 'World']. " ".join(...) rebuilds one string with single spaces. .lower() changes the case.
Watch the type at each step
A chain only works if each method exists on the type produced by the step before it. split returns a list, and lists have no lower method:
try:
"A B".split().lower()
except AttributeError as err:
print(err) # 'list' object has no attribute 'lower'Convert back to a string with join before you call another string method, or move the case change earlier in the chain.
Order changes the result
Steps are not interchangeable. Trailing whitespace stops removesuffix from matching, so trim first:
name = "report.csv\n"
print(repr(name.removesuffix(".csv"))) # 'report.csv\n'
print(repr(name.strip().removesuffix(".csv"))) # 'report'A useful default order for text cleanup is:
- Trim the ends with
strip,removeprefix, orremovesuffix. - Normalize case with
lowerorcasefold. - Remove or replace characters with
replaceortranslate. - Collapse spacing with
splitandjoin.
A reusable pipeline
Build the translation table once, outside the function. Then each call only runs the pipeline:
import string
PUNCT = str.maketrans("", "", string.punctuation)
def slug(title):
return "-".join(title.translate(PUNCT).casefold().split())
print(slug(" Hello, World! It's Python ")) # hello-world-its-pythontranslate deletes the punctuation in one pass. casefold handles case. split() with no arguments drops the extra spaces and the empty fields, and join inserts the hyphens.
Keeping long chains readable
A long chain on one line is hard to read and hard to debug. Wrap it in parentheses and put one step on each line, with a comment where a step needs one:
text = " Report_FINAL.csv\n"
result = (
text.strip()
.removesuffix(".csv")
.lower()
.replace("_", "-")
)
print(result) # report-finalTo debug, print the value after each step by temporarily splitting the chain into separate assignments.
Exercise
Write a function clean_name(s) that trims the string, collapses repeated internal whitespace to single spaces, and makes each word start with a capital letter followed by lowercase letters. What does clean_name(" aDA loveLACE ") return?
Show answer
Use " ".join(s.split()).title(). Splitting without arguments already trims both ends and collapses the spaces, so a separate strip is not needed. clean_name(" aDA loveLACE ") returns 'Ada Lovelace'.