Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string to tuple

I like to convert in a Python script the following string:

mystring='(5,650),(235,650),(465,650),(695,650)'

to a list of tuples

mytuple=[(5,650),(235,650),(465,650),(695,650)]

such that print mytuple[0] yields:

(5,650)
like image 489
Jean-Pat Avatar asked Dec 07 '22 19:12

Jean-Pat


1 Answers

I'd use ast.literal_eval:

In [7]: ast.literal_eval('(5,650),(235,650),(465,650),(695,650)')
Out[7]: ((5, 650), (235, 650), (465, 650), (695, 650))

As seen above, this returns a tuple of tuples. If you want a list of tuples, simply apply list() to the result.

like image 65
NPE Avatar answered Dec 28 '22 14:12

NPE