Python - extract coordinates from string variable

I have latitude and longitude that go into a line like this:

my_string ='(31.251, -98.877)' 

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

The problem is that sometimes a string has a variable length, so once it may look like (31.25134, -98.877) or (31.25134, -98.877435) .

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

Any idea how I could correctly extract these coordinates from this line? Thanks!

+4
source share
3 answers

How about this:

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

Should work regardless of the length of the values.

+6
source
 >>> ast.literal_eval('(31.251, -98.877)') (31.251, -98.877) 
+11
source
 (x, y) = (float(x) for x in my_string[1:-1].split(",")) 
+2
source

Source: https://habr.com/ru/post/1341377/


All Articles