0

My situation is that I'm trying to convert an array of tuples in a string format into an array of tuples.

i.e. I want to go from:

['(-109.080842,45.002073)','(-105.91517,45.002073)','(-109.080842,45.002073)']

to

[(-109.080842,45.002073),(-105.91517,45.002073),(-109.080842,45.002073)]

The purpose of this is to be able to create a shapely Polygon. It throws an error when the tuples are a string. What is the best way to go from strings to actual tuple objects?

BShaps
  • 1,344
  • 7
  • 17
  • You can parse tuples of builtin Python objects with `ast.literal_eval`. – abarnert Mar 28 '18 at 23:50
  • But, before you run off and do that—why do you have reprs of tuples as strings in the first place? If you're storing data by writing it to a file that way, there are much better ways to do it. – abarnert Mar 28 '18 at 23:50
  • @abarnert Poor coding from someone else where they manipulated the string to get it in an odd format. Turns out I can straight up just do the ast.literal_eval on the string returned from the postgres polygon type and everything works. – BShaps Mar 28 '18 at 23:57

2 Answers2

1

They're literals, so you can safely evaluate them:

>>> import ast
>>> L = ['(-109.080842,45.002073)','(-105.91517,45.002073)','(-109.080842,45.002073)']
>>> [ast.literal_eval(x) for x in L]
[(-109.080842, 45.002073), (-105.91517, 45.002073), (-109.080842, 45.002073)]
wim
  • 338,267
  • 99
  • 616
  • 750
  • [They're actually not literals.](https://docs.python.org/3/reference/expressions.html#literals) But `literal_eval` does work on them anyway. – abarnert Mar 28 '18 at 23:51
  • Hmm odd, when I printed my array of tuple strings after doing a ast.literal_eval it showed them as strings still, but it did work when passing it into the shapely Polygon. Thanks! – BShaps Mar 28 '18 at 23:53
  • @abarnert Huh. TIL. – wim Mar 28 '18 at 23:55
0

This is the functional way with ast.literal_eval:

from ast import literal_eval

lst = ['(-109.080842,45.002073)','(-105.91517,45.002073)','(-109.080842,45.002073)']

res = list(map(literal_eval, lst))

# [(-109.080842, 45.002073), (-105.91517, 45.002073), (-109.080842, 45.002073)]
jpp
  • 159,742
  • 34
  • 281
  • 339