Python - insert character into string

I think it should be relatively simple, but I cannot figure it out. I have a line representing the coordinates, +27.5916+086.5640 , and I need to put a comma between longitude and latitude, so I get +27.5916,+086.5640 .

I am browsing an API, but I cannot find anything for this.

Oh, and I have to use Python 2.7.3, since the program I am writing does not support Python 3.X.

+7
source share
4 answers

If your coordinates are c , this will work. Note that this will not work for negative values. Do you also have to deal with negatives?

 ",+".join(c.rsplit("+", 1)) 

To work with negatives.

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

OUTPUT

 +27.5916,+086.5640' 

And for the negatives:

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

This method will take care of commas if they already exist.

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

Sounds like a job for regex:

 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' 

Further reading:

+1
source

Since the second component seems to be formatted with leading zeros and a fixed number of decimal places, how about this:

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

All Articles