Fill in

Search & Replace

re.sub(pattern, replacement, text) replaces every match.

The replacement can refer back to groups with \1, \2 (or \g<name> for named groups), great for reordering:

import re
re.sub(r"(\w+) (\w+)", r"\2 \1", "Lovelace Ada")   # 'Ada Lovelace'

Or the replacement can be a function. It receives each Match and returns the string to put in its place:

def shout(m):
    return m.group().upper()

re.sub(r"fire\w*", shout, "fireflies and firewood")
# 'FIREFLIES and FIREWOOD'

A classic clean-up spell: re.sub(r"\s+", " ", text) squashes any run of spaces, tabs and newlines into one space.

Assignment

Fill in each ___:

  1. us_to_iso(text) rewrites every MM/DD/YYYY date into YYYY-MM-DD.
  2. double_numbers(text) doubles every whole number in the text.
  3. tidy_spaces(text) collapses runs of whitespace into a single space and strips the ends.