<分区>
假设我有一个表示一些嵌套列表的字符串,我想将它转换成真实的东西。我可以做到这一点,我认为:
exec "myList = ['foo', ['cat', ['ant', 'bee'], 'dog'], 'bar', 'baz']"
但是在用户可能提供字符串来执行的环境中,这可能/将是一个坏主意。有没有人对可以完成同样事情的整洁解析器有任何想法?
<分区>
假设我有一个表示一些嵌套列表的字符串,我想将它转换成真实的东西。我可以做到这一点,我认为:
exec "myList = ['foo', ['cat', ['ant', 'bee'], 'dog'], 'bar', 'baz']"
但是在用户可能提供字符串来执行的环境中,这可能/将是一个坏主意。有没有人对可以完成同样事情的整洁解析器有任何想法?
最佳答案
>>> import ast
>>> mylist = ast.literal_eval("['foo', ['cat', ['ant', 'bee'], 'dog'], 'bar', 'baz']")
>>> mylist
['foo', ['cat', ['ant', 'bee'], 'dog'], 'bar', 'baz']
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 - 如何将表示嵌套列表的字符串解析为实际列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1926741/