Instead of using a backreference with a sequence number (\1
), you can use named groups and the problem is solved:
# replace all twin digits by zeroes, but retain whitespace in between
re.sub(r"\d(?P<whitespace>\s*)\d", r"0\g<whitespace>0", "0 1")
>>> '0 0'
Turns out this trick is in fact described in the documentation of re.sub.