Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - extract coordinates from a variable string

Tags:

python

I have a latitude and longitude that come in a string like this:

my_string ='(31.251, -98.877)'

I would like to use Python to extract the coordinates from the above string.

The problem is that sometimes the string has variable length so one time it might look like this (31.25134, -98.877) or (31.25134, -98.877435).

So if I do something like my_string[9:15] to extract the last number (the longitude) if the first number (the latitude) is longer I capture the ')' too and that's not good.

Any idea how I might be able to extract those coordinates correctly from that string? Thank you!

like image 448
avatar Avatar asked Feb 25 '11 22:02

avatar


3 Answers

>>> ast.literal_eval('(31.251, -98.877)')
(31.251, -98.877)
like image 115
Ignacio Vazquez-Abrams Avatar answered Oct 21 '22 07:10

Ignacio Vazquez-Abrams


How about this:

mystr = '(31.251, -98.877)'

lat, lng = map(float, mystr.strip('()').split(','))

Should work without regard to the length of the values.

like image 40
g.d.d.c Avatar answered Oct 21 '22 08:10

g.d.d.c


(x, y) = (float(x) for x in my_string[1:-1].split(","))
like image 26
DS. Avatar answered Oct 21 '22 09:10

DS.