How do I parse a string representing a nested list into an actual list? [duplicate]

本小妞迷上赌 提交于 2019-12-17 16:44:36

问题


Say I have a string representing some nested lists and I want to convert it into the real thing. I could do this, I think:

exec "myList = ['foo', ['cat', ['ant', 'bee'], 'dog'], 'bar', 'baz']"

But in an environment where users might be supplying the string to execute this could/would be a bad idea. Does anybody have any ideas for a tidy parser that would accomplish the same thing?


回答1:


>>> import ast
>>> mylist = ast.literal_eval("['foo', ['cat', ['ant', 'bee'], 'dog'], 'bar', 'baz']")
>>> mylist
['foo', ['cat', ['ant', 'bee'], 'dog'], 'bar', 'baz']

ast.literal_eval:

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.



来源:https://stackoverflow.com/questions/1926741/how-do-i-parse-a-string-representing-a-nested-list-into-an-actual-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!