
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 ___:
us_to_iso(text)rewrites everyMM/DD/YYYYdate intoYYYY-MM-DD.double_numbers(text)doubles every whole number in the text.tidy_spaces(text)collapses runs of whitespace into a single space and strips the ends.
Fill in each ___:
us_to_iso(text)rewrites everyMM/DD/YYYYdate intoYYYY-MM-DD.double_numbers(text)doubles every whole number in the text.tidy_spaces(text)collapses runs of whitespace into a single space and strips the ends.
main.py Python sleeping
Press Run to try your code, then Check to test it.