gpt4 book ai didi

python - 将列表的字符串表示形式转换为实际的列表对象

转载 作者:IT老高 更新时间:2023-10-28 21:33:32 25 4
gpt4 key购买 nike

我有一个看起来与列表相同的字符串,比如说:

fruits = "['apple', 'orange', 'banana']"

将其转换为列表对象的方法是什么?

最佳答案

>>> fruits = "['apple', 'orange', 'banana']"
>>> import ast
>>> fruits = ast.literal_eval(fruits)
>>> fruits
['apple', 'orange', 'banana']
>>> fruits[1]
'orange'

正如评论中指出的 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.

关于python - 将列表的字符串表示形式转换为实际的列表对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10775894/

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