首页 > 解决方案 > Python literal_eval 无效语法

问题描述

当我试图这样做时:

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']

标签: pythonlist

解决方案


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

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

推荐阅读