On this page
re.subn
Prev: re.sub | Up: re
Rel: re.compile, re.error, re.escape, re.findall
Ref: docs.python.org — re.subn
Tags: #public #python3 #stdlib #re
Import
import re
from re import subn
Signature & Overview
re.subn(pattern, repl, string, count=0, flags=0)
Return a 2-tuple containing (new_string, number).
Usage
import re
new_text, count = re.subn(r"\d+", "X", "a1 b2 c3")
assert new_text == "aX bX cX" and count == 3
Gotchas
- Returns
(new_string, number_of_subs): Identical tore.sub(), plus the exact count of replacements made—handy for detecting whether a rewrite actually changed anything. - Same backslash rules as
re.sub(): Use alambdareplacement when inserting arbitrary literal text.
REPL Inspect
from re import subn
help(subn)
Linked from
Related notes
- tuts/python3/stdlib_module/re/sub Linked here; links to this page; shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/re/compile Linked here; shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re/error Linked here; shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re/escape Linked here; shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re/findall Linked here; shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re/finditer shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re/fullmatch shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re/match shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re/Match_class shared tags: #re, #stdlib