Python literal_eval无效语法

2024-07-07 08:27:52 发布

您现在位置:Python中文网/ 问答频道 /正文

当我尝试这样做时:

literal_eval('[Alices Adventures in Wonderland, and, Through the Looking-Glass, by, Lewis Carroll]')

我得到这个错误:

  File "<unknown>", line 1
    [Alices Adventures in Wonderland, and, Through the Looking-Glass, by, Lewis Carroll]
                     ^
SyntaxError: invalid syntax

我希望得到这样的列表对象:

[Alices Adventures in Wonderland, and, Through the Looking-Glass, by, Lewis Carroll]

编辑:

我想得到的是一个列表,里面有字符串元素。这不起作用,因为在literal_eval之后,列表中的对象不是字符串

所以,最后,为了找到我的解决方案,我做了以下几点:

'[Alices Adventures in Wonderland, and, Through the Looking-Glass, by, Lewis Carroll]'.strip("[]").split(",")

这使得输出为:

['Alices Adventures in Wonderland', ' and', ' Through the Looking-Glass', ' by', ' Lewis Carroll']

Tags: andthein列表byevalthroughlewis
2条回答

在列表中,字符串项用引号括起来:

literal_eval('["Alices Adventures in Wonderland", "and", "Through the Looking-Glass", "by", "Lewis Carroll"]')
x = ['[Alices Adventures in Wonderland, and, Through the Looking-Glass, by, Lewis Carroll]'] #create list that has string literal list
print(x) #observe the list is printed with the brackets as a literal
print(type(x)) #here we are printing the class type of list 

输出

['[Alices Adventures in Wonderland, and, Through the Looking-Glass, by, Lewis Carroll]']
<class 'list'>

相关问题 更多 >