re.sub
str.replace with patterns. The replacement is a small template language — \1 and \g<name> insert groups — or a function that computes each replacement. re.subn does the same and also returns how many replacements were made; both exist as Pattern.sub / Pattern.subn.
Demo
import re re.sub('(\\w+), (\\w+)', '\\2 \\1', 'Lovelace, Ada')
\g<1>0 is the way to write "group 1, then the digit 0" — \10 would mean group 10. A group that did not take part in a match is replaced by an empty string (since Python 3.5). In the empty-match subn case, x* matches the empty string at every position, so a dash lands between every character and at both ends. Errors report positions inside repl, counted from 0.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| pattern | str | re.Pattern | yes | What to replace, as a raw-string regular expression. |
| repl | str | callable | yes | Template string (\1, \g<name>, \g<0>, \n …) or a function taking the Match and returning a str. |
| string | str | yes | The input text (not modified — strings are immutable). |
| count | int | no (0) | Maximum number of replacements; 0 means all. Pass it by keyword (positional is deprecated since 3.13). |
| flags | re.RegexFlag | int | no (0) | Flags such as re.IGNORECASE. Pass by keyword. |
Return value
str — A new string with the matches replaced (subn returns a (new_string, number_of_replacements) tuple).
Common patterns
import re clean = re.sub(r'\s+', ' ', text).strip()
import re repl = {'cat': 'dog', 'red': 'blue'} pat = re.compile('|'.join(map(re.escape, repl))) result = pat.sub(lambda m: repl[m.group()], text)
import re result = re.sub(r'\{name\}', lambda m: user_input, template)
import re new_text, n = re.subn(r'\bcolour\b', 'color', text) if n: print(f'fixed {n} spellings')
Examples
Pitfalls
import re re.sub(r'(a)', r'\2', 'a')
import re re.sub(r'(a)', r'\1\1', 'a')
import re path = r'C:\data' re.sub(r'DIR', path, 'cd DIR')
import re path = r'C:\data' re.sub(r'DIR', lambda m: path, 'cd DIR')
import re re.sub(r'(a)', r'\10', 'a')
import re re.sub(r'(a)', r'\g<1>0', 'a')
import re re.sub(r'(?P<word>\w+)', r'\g<wrod>', 'hi')
import re re.sub(r'(?P<word>\w+)', r'<\g<word>>', 'hi')
When to use
- Replacing text that varies: numbers, whitespace runs, dates, names
- Rearranging parts of each match with groups
- Computing each replacement with a function
- Fixed text → str.replace (faster, no escaping rules)
- Character-for-character mapping → str.translate
- Several unrelated fixed replacements → one compiled alternation + dict lookup (see patterns)
Notes
FAQ
Write \1, \2 … or \g<name> for named groups in a raw-string repl: re.sub(r'(\w+) (\w+)', r'\2 \1', 'Ada Lovelace') gives 'Lovelace Ada'. \g<0> is the whole match.