我想取字符串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
Run Code Online (Sandbox Code Playgroud)
但这给了我0.7133,2.25378.我究竟做错了什么?
And*_*ark 94
您应该使用原始字符串进行正则表达式,请尝试以下操作:
coord_re = re.sub(r"(\d), (\d)", r"\1,\2", coords)
Run Code Online (Sandbox Code Playgroud)
使用当前代码,替换字符串中的反斜杠将转义数字,因此您将替换所有匹配项,相当于chr(1) + "," + chr(2):
>>> '\1,\2'
'\x01,\x02'
>>> print '\1,\2'
,
>>> print r'\1,\2' # this is what you actually want
\1,\2
Run Code Online (Sandbox Code Playgroud)
任何时候你想在字符串中留下反斜杠,使用r前缀,或者转义每个反斜杠(\\1,\\2).
Pet*_*rin 13
Python将其解释\1为ASCII值为1的字符,并将其传递给sub.
使用原始字符串,Python不解释它\.
coord_re = re.sub(r"(\d), (\d)", r"\1,\2", coords)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
43520 次 |
| 最近记录: |