11

I think this should be relatively simple, but I can't figure it out. I have a string that represents coordinates, +27.5916+086.5640 and I need to put a comma in between the longitude and latitude so I get +27.5916,+086.5640.

I'm looking through the API but I can't seem to find something for this.

Oh and I have to use Python 2.7.3 since the program I writing for doesn't support Python 3.X.

4 Answers 4

9

If your coordinates are c, then this would work. Note, however, this will not work for negative values. Do you have to deal with negatives as well?

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

For dealing with negatives as well.

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

OUTPUT

+27.5916,+086.5640'

And for negatives:

>>> c = "+27.5916-086.5640"
>>> parts = re.split("([\+\-])", c)
>>> parts.insert(3, ',')
>>> "".join(parts[1:])
'+27.5916,-086.5640'
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a bunch, both of you. This is perfect. I was looking in the string section of the API and found nothing. Off to go read more about stuff (python newbie extraordinaire here)
4

This method will take care of commas if they are already there.

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

Comments

3

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'

Comments

1

Sounds like a job for a regular expression:

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:

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.