在 Python 中将列表的字符串表示转换为列表
pythonserver side programmingprogramming更新于 2026/1/13 8:12:17
由于 Python 处理各种数据类型,我们会遇到列表以字符串形式出现的情况。在本文中,我们将了解如何将字符串转换为列表。
使用 strip 和 split
我们首先应用 strip 方法删除方括号,然后应用 split 函数。以逗号为参数的 split 函数从字符串创建列表。
示例
stringA = "[Mon, 2, Tue, 5,]"
# 给定字符串
print("给定字符串", stringA)
print(type(stringA))
# 字符串到列表
res = stringA.strip('][').split(', ')
# 结果及其类型
print("final list", res)
print(type(res))
输出
运行上述代码得到以下结果 −
Given string [Mon, 2, Tue, 5,] final list ['Mon', '2', 'Tue', '5,']
使用 json.loads
json 模块可以直接将字符串转换为列表。我们只需将字符串作为参数传递即可应用该函数。我们在这里只能考虑数字元素。
示例
import json
stringA = "[21,42, 15]"
# 给定字符串
print("给定字符串", stringA)
print(type(stringA))
# 字符串列表
res = json.loads(stringA)
# 结果及其类型
print("final list", res)
print(type(res))
输出
运行上述代码得到以下结果 −
给定字符串 [21,42, 15] 最终列表 [21, 42, 15]
使用 ast.literal_eval
ast 模块为我们提供了 literal_eval,它可以直接将字符串转换为列表。我们只需将字符串作为参数提供给 literal_eval 方法即可。我们在这里只能考虑数字元素。
示例
import ast
stringA = "[21,42, 15]"
# 给定字符串
print("给定字符串", stringA)
print(type(stringA))
# 字符串到列表
res = ast.literal_eval(stringA)
# 结果及其类型
print("最终列表", res)
print(type(res))
输出
运行上述代码得到以下结果 −
给定字符串 [21,42, 15] 最终列表 [21, 42, 15]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

