我想取字符串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
。我究竟做错了什么?
我想取字符串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
。我究竟做错了什么?
coords.replace(' ', '')
Answers:
您应该对正则表达式使用原始字符串,请尝试以下操作:
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
)进行转义。
\1
被称为xCoord,是否有可能指示re.sub
将子字符串替换为组名称,从而re.sub(r"(\d), (\d)", r"\1,\2", coords)
导致字符串字面量xCoord,52.25378
\1
将其替换为一些奇怪的Unicode字符。
re.sub(r'(?<=\d), (?=\d)', ',', coords)
。