SyntaxStudy
Sign Up
Python re.sub — Substitution
Python Intermediate 4 min read

re.sub — Substitution

re.sub

re.sub(pattern, replacement, string) replaces all matches. The replacement can reference groups with \1 or \g<name>.

Example
import re

text = "John Smith, Jane Doe"
# Swap first and last name
result = re.sub(r"(\w+) (\w+)", r"\2, \1", text)
print(result)
# Smith, John, Doe, Jane
Pro Tip

Pass a callable as replacement for dynamic substitutions.