Python Glossary Русский

all Python 3refunction

re.sub

replacement

Replace all matches of the pattern in the string with a replacement.

Syntax

re.sub(pattern, repl, string, count=0)

When neither the pattern nor the replacement uses regex syntax, reach for str.replace: it is faster and you avoid escaping dots, pluses and brackets. Backslashes in the replacement follow their own rules — a group reference is \1 or \g<name>, and '\n' without the r prefix becomes a real newline. The original string is never modified in place, so you have to assign the result.

Examples

import re
print(re.sub(r'\d+', '#', 'a1b22c'))   # → a#b#c
print(re.sub(r'\d', '#', 'a1b2c3', count=2))   # → a#b#c3
print(re.sub(r'(\w+)@(\w+)', r'\2:\1', 'user@host'))   # → host:user
print(re.sub(r'\d+', lambda m: str(int(m.group()) * 2), 'a2 b10'))   # → a4 b20
print(re.sub(r'z+', '-', 'abc'))   # → abc

See also

Open in the full glossarydocs.python.orgReport an inaccuracy