Transform Text with sub and split
Core idea
re.sub replaces non-overlapping matches; it accepts replacement text or a callable taking a Match. re.split splits around matching separators. Capturing parentheses in a split pattern also include captured separator text in the result.
The character class targets spaces and tabs, not newlines.
Split mixed separators
import res = "a,b;c"print(re.split(r"[,;]",s))print(re.split(r"([,;])",s))Capturing the separators retains them as additional items.
Common mistake
Replacement templates have their own backslash rules. For literal replacement text supplied by a user, a callable returning that text avoids interpreting backreferences. re.escape is for literal patterns, not replacement templates.
Practice
Collapse runs of ASCII spaces and tabs to a single space, preserving newlines and not trimming the ends.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Replacement and splitting
Check your understanding of substitution and splitting.
What is printed?
import reprint(re.sub(r"[0-9]+","-","A123B"))What is printed?
import reprint(re.split(r"(:)","a:b"))What argument does a replacement callable receive?
Which operation replaces only the first match?