re.sub() replaces text matching a regular-expression pattern and returns a new string, leaving the original string unchanged. section 8.3.2 section 8.6
Replace lowercase and uppercase vowels
import re text = 'Apples and Bananas!' vowel = 'o' text = re.sub('[aeiou]', vowel, text) text = re.sub('[AEIOU]', vowel.upper(), text) print(text) # Opplos ond Bononos! section 8.3.2
The call follows a compact pattern:
- Pass the pattern to search, the replacement text, and the input string. section 17.1.4
- Use a character class such as [aeiou] when any listed character should match. section 8.3.2
- By default, replace every leftmost, non-overlapping match; count and flags can also be supplied. section 17.1.4
- Replace placeholders such as <noun> with supplied values, or remove unwanted characters with an empty replacement. section 17.1.4 section 18.3.1
sub(pattern, repl, string, count=0, flags=0) Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl.
Use the signature as a quick reference for arguments and the default replacement behavior. section 17.1.4
