在 re.sub 替换模式中处理对捕获组的回溯引用

我想取字符串 0.71331, 52.25378并返回 0.71331,52.25378-也就是说,只需查找一个数字、一个逗号、一个空格和一个数字,然后去掉空格。

这是我现在的代码:

coords = '0.71331, 52.25378'
coord_re = re.sub("(\d), (\d)", "\1,\2", coords)
print coord_re

但是这给了我 0.7133,2.25378。我做错了什么?

79838 次浏览

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

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

使用当前代码,替换字符串中的反斜杠将转义数字,因此您将替换所有相当于 chr(1) + "," + chr(2)的匹配项:

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

任何时候您想在字符串中保留反斜杠,使用 r前缀,或者转义每个反斜杠(\\1,\\2)。

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

使用原始字符串,其中 Python 不解释 \

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

这是涵盖权利在开始的 re文档,如果你需要更多的信息。