Search code examples
pythonstringsplitnumberspython-re

Best way to parse lat and lon string


I want to convert one string, which contains lat and lon values, to two floats. However, the string may be separated by mixing commas and spaces, such as 28.111,77.222, 28.111, 77.222, 28.111 77.222, 28.111 77.222.

I have tried this method:

import re

test = '28.111,77.222'
res = re.findall(r'\d+', test)
lat = res[0]
lon = res[1]

It only works for int, how about float numbers like this case?


Solution

  • import re
    
    examples = "28.111,77.222", "28.111, 77.222", "28.111 77.222", "28.111   77.222"
    
    # split on spaces and/or commas
    [re.split(",| ", example) for example in examples]
    # [['28.111', '77.222'], ['28.111', '', '77.222'], ['28.111', '77.222'], ['28.111', '', '', '77.222']]