re.sub replaces matches. The replacement can be a string with \1 or a function of the match.
Goal
Mask digits in a phone line and rewrite totals.
import re
print(re.sub(r"\d", "#", "call 0712345678"))import re
print(re.sub(r"(\d{4})-(\d{3})-(\d{3})", r"\1***", "0712-345-678"))import re
def double(m):
return str(int(m.group()) * 2)
print(re.sub(r"\d+", double, "Nairobi 12 Mombasa 9"))import re
print(re.sub(r"\s+", ",", "Nairobi 12 10.5", count=2))