开发者

python - extract coordinates from a variable string

开发者 https://www.devze.com 2023-02-13 17:57 出处:网络
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.

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 开发者_如何学JAVAlast 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!


>>> ast.literal_eval('(31.251, -98.877)')
(31.251, -98.877)


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.


(x, y) = (float(x) for x in my_string[1:-1].split(","))
0

精彩评论

暂无评论...
验证码 换一张
取 消