On this page
re.sub
Prev: re.split | Up: re | Next: re.subn
Rel: re.compile, re.error, re.escape, re.findall
Ref: docs.python.org — re.sub
Tags: #public #python3 #stdlib #re
Import
import re
from re import sub
Signature & Overview
re.sub(pattern, repl, string, count=0, flags=0)
Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl. repl can be either a string or a callable;
Usage
import re
assert re.sub(r"\s+", "-", "hello world\t!") == "hello-world-!"
# Pass a function for dynamic replacements
doubled = re.sub(r"\d+", lambda m: str(int(m.group()) * 2), "a=3 b=10")
assert doubled == "a=6 b=20"
Gotchas
- Replacement strings interpret backslashes: If
replis a dynamic string that might contain\1or\n, passlambda _: replinstead ofrepldirectly. count=0means replace all: Passcount=1to replace only the first match (and use keywordcount=/flags=to avoid positional mix-ups).
REPL Inspect
from re import sub
help(sub)
Linked from
Related notes
- tuts/python3/stdlib_module/re/split Linked here; links to this page; shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re/subn 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