re is Python’s standard-library module for describing text patterns and matching, replacing, or splitting text. It is useful when ordinary string methods would require manually writing several search-and-replace steps. section 8.6 section 14.1.2
The core operations demonstrated here are:
- Use re.sub(pattern, replacement, text) to create a modified string while leaving the original unchanged. section 8.3.2 section 8.6
- Use character classes such as [aeiou] to match one character from a set, and add + to match one or more consecutive characters. section 14.1.2
- Use re.match() for a pattern beginning at the start of text, re.search() for a match beginning anywhere, and re.split() for pattern-based splitting. section 14.1.2 section 15.1.1
Replace vowels
>>> import re >>> pattern = '[aeiou]' >>> re.sub(pattern, 'o', 'Apples and bananas!') 'Applos ond bononos!' For both cases, apply two substitutions when preserving capitalization: >>> text = 'Apples and Bananas!' >>> re.sub('[AEIOU]', 'O', re.sub('[aeiou]', 'o', text)) 'Opplos ond Bononos!' section 8.3.2
Match initial consonants
Build a character class from the lowercase consonants, then match one or more at the beginning of a word: >>> consonants = 'bcdfghjklmnpqrstvwxyz' >>> re.match(f'[{consonants}]+', 'chair') <re.Match object; span=(0, 2), match='ch'> >>> re.match(f'[{consonants}]+', 'apple') >>> type(re.match(f'[{consonants}]+', 'apple')) <class 'NoneType'> section 14.1.2
>>> vowel = 'o' >>> re.sub(pattern, vowel, 'Apples and bananas!') 'Applos ond bononos!'
Run a minimal re.sub example and inspect the returned replacement string. section 8.3.2

