Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested string to tuple python

Tags:

python

my String looks like:

"('f', ('d', ('a', 'b')), 'g')"

I want to convert that to tuple. How can do that... I will use that in drawing a dendogram

Edit: additional explanation: my code and output's (print's):

print type(myString)                     # <type 'str'>
print myString                           #('f',('d',('a','b')),'g')
myString = ast.literal_eval(myString)
print type(myString)                     #<type 'tuple'>
print myString                           #('f', ('d', ('a', 'b')), 'g')

for tuple in myString:                   #f
    print tuple                          #('d', ('a', 'b'))
                                         #g
like image 468
klonitklonit Avatar asked Dec 19 '25 00:12

klonitklonit


2 Answers

You can do this with ast.literal_eval - for example:

>>> import ast
>>> s = "('f', ('d', ('a', 'b')), 'g')"
>>> ast.literal_eval(s)
('f', ('d', ('a', 'b')), 'g')

The documentation for that function says:

Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.

like image 78
Mark Longair Avatar answered Dec 20 '25 15:12

Mark Longair


Use ast.literal_eval.

This will not let some malicious scripts run from the string provided as with eval.

like image 28
ovgolovin Avatar answered Dec 20 '25 14:12

ovgolovin