Handling backreferences to capturing groups in re.sub replacement pattern

You should be using raw strings for regex, try the following:

coord_re = re.sub(r"(\d), (\d)", r"\1,\2", coords)

With your current code, the backslashes in your replacement string are escaping the digits, so you are replacing all matches the equivalent of chr(1) + "," + chr(2):

>>> '\1,\2'
'\x01,\x02'
>>> print '\1,\2'
,
>>> print r'\1,\2'   # this is what you actually want
\1,\2

Any time you want to leave the backslash in the string, use the r prefix, or escape each backslash (\\1,\\2).


Python interprets the \1 as a character with ASCII value 1, and passes that to sub.

Use raw strings, in which Python doesn't interpret the \.

coord_re = re.sub(r"(\d), (\d)", r"\1,\2", coords)

This is covered right in the beginning of the re documentation, should you need more info.