4
>>> import ast
>>> string = '[Small, Medium, Large, X-Large]'
>>> print string
[Small, Medium, Large, X-Large]
>>> string = ast.literal_eval(string)
Traceback (most recent call last):  
    File "<pyshell#26>", line 1, in <module>
         string = ast.literal_eval(string)
    File "C:\Python27\lib\ast.py", line 80, in literal_eval
        return _convert(node_or_string)
    File "C:\Python27\lib\ast.py", line 60, in _convert
        return list(map(_convert, node.elts))
  File "C:\Python27\lib\ast.py", line 79, in _convert
    raise ValueError('malformed string')
ValueError: malformed string

怎么修?

4

2 回答 2

15

ast.literal_eval()仅接受包含有效 Python 文字结构(字符串、数字、元组、列表、字典、布尔值和None)的字符串。

这是一个仅包含以下文字结构的有效 Python 表达式:

["Small", "Medium", "Large", "X-Large"]

这不是:

[Small, Medium, Large, X-Large]

创建有效字符串的两种方法:

string = '["Small", "Medium", "Large", "X-Large"]'
string = "['Small', 'Medium', 'Large', 'X-Large']"
于 2012-04-11T20:20:25.107 回答
3

您的字符串不是有效列表。如果是字符串列表,则需要引号。

例如:

string = '["Small", "Medium", "Large", "X-Large"]'
于 2012-04-11T20:18:04.967 回答