Python Function Reference

re.sub

Replace matches of a regular expression.

Python 3.13
re.sub(pattern, repl, string, count=0, flags=0)
  • =default value
pattern
The regular expression.
str | Pattern
repl
A replacement string, or a function that receives a Match object and returns a string.
str | Callable
string
The source string.
str
count
The maximum number of replacements; 0 by default, which means all.
intOptional
flags
Flags, 0 (no flags) by default; combine several with |.
intOptional
re.IGNORECASEre.MULTILINEre.DOTALLre.VERBOSEre.ASCII

Return value

A new string with the replacements; the original is not changed.

Examples

Replacing spaces with a hyphen

Python 3.13
import re
print(re.sub(r'\s+', '-', 'hello world'))
hello-world

Replacing with a function

Python 3.13
import re
print(re.sub(r'\d+', lambda match: str(int(match.group()) * 2), 'a1 b22'))
a2 b44

Details

The replacement string can refer to groups: \1 or \g<name>. Since Python 3.13, pass count and flags by name: passing them positionally is deprecated.

See also