Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

re.sub

Replaces non-overlapping regex matches using a replacement template with group references or a callable.

Version: Python 3.14; repository image, production runtime not attested

Syntax

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

Replaces non-overlapping regex matches using a replacement template with group references or a callable.

A positive replacement limit leaves subsequent matches untouched, and a callable receives the match object.

Replace nonoverlapping matches from left to right. A replacement string is a template that may contain group references; a replacement function receives a Match and supplies the replacement directly. count=0 permits all replacements. With count=1 the example increments the first number from 3 to 4 and retains y7. An unknown ASCII-letter escape such as \q in a replacement template raises re.PatternError. The same string returned by a callable remains literal.

import re
assert re.sub(r"(\w+)=(\d+)", r"\2:\1", "x=3") == "3:x"
assert re.sub(r"\d+", lambda m: str(int(m[0]) + 1), "x3 y7", count=1) == "x4 y7"
assert re.sub("z", "x", "abc") == "abc"
try:
    re.sub("a", r"\q", "a")
except re.PatternError:
    pass
else:
    raise AssertionError
assert re.sub("a", lambda m: r"\q", "a") == r"\q"

Examples

import re
print(re.sub(r"\d+", lambda m: str(int(m.group()) + 1), "x3 y7", count=1))

Result

x4 y7

Replace nonoverlapping matches from left to right. A replacement string is a template that may contain group references; a replacement function receives a Match and supplies the replacement directly. count=0 permits all replacements. With count=1 the example increments the first number from 3 to 4 and retains y7. An unknown ASCII-letter escape such as `\q` in a replacement template raises re.PatternError. The same string returned by a callable remains literal.

Sources