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
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.
Use ast.literal_eval.
This will not let some malicious scripts run from the string provided as with eval.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With