Substitution in Python
Rewriting text with re.sub, including callbacks.
import re
messy = "call me maybe, ok?"
tidy = re.sub(r"\s+", " ", messy)
redacted = re.sub(r"\d{3}-\d{4}", "XXX-XXXX", "ring 555-1234 now")
def shout_word(match):
return match.group(0).upper()
emphatic = re.sub(r"\bmaybe\b", shout_word, tidy)
swapped = re.sub(r"(\w+)@(\w+)", r"\2 at \1", "ada@lovelace")
How it works
sub(r'\s+', ' ', ...)collapses whitespace.- A function replacement transforms each match.
- Backreferences like
\2 at \1reorder captures.
Keywords and builtins used here
defreturnshout_word
The run, in numbers
- Lines
- 14
- Characters to type
- 314
- Tokens
- 111
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 63 seconds.
Step 3 of 5 in Regular expressions, step 3 of 41 in Domain tools.