I have a long string of coordinates divided by commas.
['22.98795, 74.5936', '55.26964, 124.43686', '39.34479, 124.53541']
What is the easiest way to convert this string into a list of coordinates like the one below?
[(22.98795, 74.5936), (55.26964, 124.43686), (39.34479, 124.53541)]
I hope there is an easier solution than this
coords = "['22.98795, 74.5936', '55.26964, 124.43686', '39.34479, 124.53541']"
x = coords.split("', '")
x[0] = x[0][2:]
x[-1] = x[-1][:-2]
>>> from ast import literal_eval
>>> coords = "['22.98795, 74.5936', '55.26964, 124.43686', '39.34479, 124.53541']"
>>> l = literal_eval(coords)
>>> l
['22.98795, 74.5936', '55.26964, 124.43686', '39.34479, 124.53541']
>>> [tuple(map(float, i.split(','))) for i in l]
[(22.98795, 74.5936), (55.26964, 124.43686), (39.34479, 124.53541)]
As a one-liner:
coords = [tuple(map(float, i.split(','))) for i in literal_eval(coords)]
Or, since 22.98795, 74.5936
happens to be a valid literal for a tuple, use literal_eval
for it again:
coords = list(map(literal_eval, literal_eval(coords)))