typestar

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

  1. sub(r'\s+', ' ', ...) collapses whitespace.
  2. A function replacement transforms each match.
  3. Backreferences like \2 at \1 reorder captures.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 5 in Regular expressions, step 3 of 41 in Domain tools.

← Previous Next →