Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a string which represents a list of tuples

I have strings which look like this one:

"(8, 12.25), (13, 15), (16.75, 18.5)"

and I would like to convert each of them into a python data structure. Preferably a list (or tuple) of tuples containing a pair of float values.

I could do that with eval("(8, 12.25), (13, 15), (16.75, 18.5)") which gives me a tuple of tuples, but I don't think naively evaluating external information would be a wise decision.

So I wondered what an elegant pythonic solution might look like.

like image 746
tosh Avatar asked Nov 27 '09 18:11

tosh


1 Answers

>>> import ast
>>> print ast.literal_eval("(8, 12.25), (13, 15), (16.75, 18.5)")
((8, 12.25), (13, 15), (16.75, 18.5))
like image 78
nosklo Avatar answered Sep 21 '22 02:09

nosklo