user4659009
user4659009

Reputation: 685

How to split coordinates in a string into a list of smaller lists

I am trying to turn a string of coordinates "(x1, y1), (x2, y2)" into [[x1,y1], [x2,y2]] where all the coordinates are converted into floats as well.

My current code doesn't seem to trim whitespace of the y coordinates nor does it convert the strings into floats.

coordinates = "(-89.38477, 26.6671), (-89.38477, 27.13737), (-88.81348, 27.13737), (-88.81348, 26.6671)"
for x in re.findall("\((.*?)\)", coordinates):
        final_coordinates = x.lstrip().split(',')

Upvotes: 2

Views: 1295

Answers (1)

alecxe
alecxe

Reputation: 473873

One option could be to enclose the coordinates into square brackets and use literal_eval():

>>> from ast import literal_eval
>>> coordinates = "(-89.38477, 26.6671), (-89.38477, 27.13737), (-88.81348, 27.13737), (-88.81348, 26.6671)"
>>>
>>> data = list(literal_eval(coordinates))
>>> data
[(-89.38477, 26.6671), (-89.38477, 27.13737), (-88.81348, 27.13737), (-88.81348, 26.6671)]

Upvotes: 5

Related Questions