如何将列表的字符串表示形式转换为列表? [英] How to convert string representation of list to a list?
问题描述
我想知道将如下列表的字符串表示形式转换为 list
的最简单方法是什么:
I was wondering what the simplest way is to convert a string representation of a list like the following to a list
:
x = '[ "A","B","C" , " D"]'
即使在用户在逗号之间和引号内放置空格的情况下,我也需要处理它并将其转换为:
Even in cases where the user puts spaces in between the commas, and spaces inside of the quotes, I need to handle that as well and convert it to:
x = ["A", "B", "C", "D"]
我知道我可以使用 strip()
和 split()
去除空格并检查非字母字符.但是代码变得非常混乱.是否有我不知道的快速功能?
I know I can strip spaces with strip()
and split()
and check for non-letter characters. But the code was getting very kludgy. Is there a quick function that I'm not aware of?
推荐答案
>>> import ast
>>> x = '[ "A","B","C" , " D"]'
>>> x = ast.literal_eval(x)
>>> x
['A', 'B', 'C', ' D']
>>> x = [n.strip() for n in x]
>>> x
['A', 'B', 'C', 'D']
使用 ast.literal_eval
,您可以安全地计算表达式节点或包含 Python 文字或容器显示的字符串.提供的字符串或节点只能包含以下 Python 文字结构:字符串、字节、数字、元组、列表、字典、布尔值和 None
.
With
ast.literal_eval
you can safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, booleans, andNone
.
这篇关于如何将列表的字符串表示形式转换为列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!