将列表的字符串表示形式转换为实际的列表对象 [英] Converting a string representation of a list into an actual list object
问题描述
我有一个看起来与列表相同的字符串,比方说:
I have a string that looks identical to a list, let's say:
fruits = "['apple', 'orange', 'banana']"
将其转换为列表对象的方式是什么?
What would be the way to convert that to a list object?
推荐答案
>>> fruits = "['apple', 'orange', 'banana']"
>>> import ast
>>> fruits = ast.literal_eval(fruits)
>>> fruits
['apple', 'orange', 'banana']
>>> fruits[1]
'orange'
如评论中所指出的, ast.literal_eval 是安全.从文档中:
As pointed out in the comments ast.literal_eval is safe. From the docs:
安全地评估表达式节点或包含Python的字符串 表达.提供的字符串或节点只能由 以下Python文字结构:字符串,数字,元组,列表, dicts,booleans和None.
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.
这可用于安全地评估包含Python的字符串 来自不受信任来源的表达式,无需解析 珍惜自己.
This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.
这篇关于将列表的字符串表示形式转换为实际的列表对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!