Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

re.subn

Returns transformed text together with the number of substitutions performed.

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

Syntax

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

Returns transformed text together with the number of substitutions performed.

A replacement equal to the matched text still counts as a substitution.

Use subn to record how many matches were replaced alongside the resulting text. It accepts the same group-reference templates or match callbacks and count limit as sub. Replacing a with a in aba counts two replacements even though the text is identical. The absent z produces the original text and zero.

import re
s, n = re.subn("a", "a", "aba", count=1)
assert (s, n) == ("aba", 1)
assert re.subn(r"\d", lambda m: "#" * int(m[0]), "a2b1") == ("a##b#", 2)
assert re.subn("z", "x", "aba") == ("aba", 0)

Examples

import re
print(re.subn("a", "a", "aba"))
print(re.subn("z", "x", "aba"))

Result

('aba', 2)
('aba', 0)

Use subn to record how many matches were replaced alongside the resulting text. It accepts the same group-reference templates or match callbacks and count limit as sub. Replacing a with a in aba counts two replacements even though the text is identical. The absent z produces the original text and zero.

Sources