gpt4 book ai didi

python - 嵌套字符串到元组python

转载 作者:太空宇宙 更新时间:2023-11-03 12:49:59 24 4
gpt4 key购买 nike

我的字符串看起来像:

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

我想把它转换成元组。怎么做到的...我会用它来画树状图

编辑:补充说明:我的代码和输出(打印):

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

最佳答案

您可以使用 ast.literal_eval 执行此操作- 例如:

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

documentation对于该功能说:

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.

关于python - 嵌套字符串到元组python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12876974/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com