re.sub
re.sub(pattern, replacement, string) replaces all matches. The replacement can reference groups with \1 or \g<name>.
re.sub(pattern, replacement, string) replaces all matches. The replacement can reference groups with \1 or \g<name>.
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
Pass a callable as replacement for dynamic substitutions.