Python - 将一个字符插入到字符串中

11

我认为这应该相对简单,但是我无法弄清楚。 我有一个表示坐标的字符串,+27.5916+086.5640,我需要在经度和纬度之间放置逗号,以便得到+27.5916,+086.5640

我正在查看API,但似乎找不到相关的方法。

哦,我必须使用Python 2.7.3,因为我编写的程序不支持Python 3.X。

4个回答

9
如果您的坐标是c,那么这将起作用。但请注意,这对负值无效。您还需要处理负数吗?
",+".join(c.rsplit("+", 1))

为了处理负面的情况,同样适用。
import re
parts = re.split("([\+\-])", c)
parts.insert(3, ',')
print "".join(parts[1:])

输出

+27.5916,+086.5640'

对于否定情况:

>>> c = "+27.5916-086.5640"
>>> parts = re.split("([\+\-])", c)
>>> parts.insert(3, ',')
>>> "".join(parts[1:])
'+27.5916,-086.5640'

非常感谢你们两位。这太完美了。我在API的字符串部分找不到任何东西。我要去阅读更多相关资料(作为一个Python新手)。 - user1777900

4

如果逗号已经存在,此方法将自动处理。

str = '-27.5916-086.5640'
import re
",".join(re.findall('([\+-]\d+\.\d+)',str))
'-27.5916,-086.5640'

3

由于第二个组件似乎采用前导零和固定数量的小数位进行格式化,那么可以这样做:

>>> s='+27.5916+086.5640'
>>> s[0:-9]+','+s[-9:]
'+27.5916,+086.5640'

1

这似乎是正则表达式的工作:

Python 2.7.3 (default, Aug 27 2012, 21:19:01) 
[GCC 4.2.1 Compatible Apple Clang 4.0 ((tags/Apple/clang-421.0.57))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> coords = '+27.5916+086.5640'
>>> lat, long = re.findall('[+-]\d+\.\d+', coords)
>>> ','.join((lat, long))
'+27.5916,+086.5640'

进一步阅读:


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接