I'm trying to convert a string that looks like this into an array of tuples
"[(1,2), (2,3), (4,5)]"
-> [(1,2), (2,3), (4,5)]
Here is the body of code I would like to populate:
def convert_to_polygon(polygon_string):
return polygon_array
Should I be using a python library? Does one exist for this job?
You can use ast.literal_eval
:
>>> import ast
>>> s = '{{1,2},{2,3},{4,5}}'
>>> polygon_array = ast.literal_eval(s.replace('{', '(').replace('}', ')'))
>>> polygon_array
((1, 2), (2, 3), (4, 5))
>>> polygon_array[1][0]
2
Use list(polygon_array)
if you want a list of tuples.
Collected from the Internet
Please contact javaer1[email protected] to delete if infringement.
Comments