Python Glossary Русский

all Python 3refunction

re.subn

replacement

Like sub(), but return a tuple (new_string, number_of_substitutions).

Syntax

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

Use it when you need to know whether anything was replaced: comparing the result against the original is unreliable, since the replacement text may equal what was matched and leave the string looking untouched. The second value counts substitutions actually performed, so with count=N it never exceeds N even when the string holds more matches.

Examples

import re
print(re.subn(r'\d', '#', 'a1b2'))   # → ('a#b#', 2)
print(re.subn(r'\d', '#', 'abc'))   # → ('abc', 0)
print(re.subn(r'\d', '#', 'a1b2c3', count=2))   # → ('a#b#c3', 2)
text, n = re.subn(r'\s+', ' ', 'a  b   c')
print(n)   # → 2

See also

Open in the full glossarydocs.python.orgReport an inaccuracy