Python 的 literal_eval 表示字符串 'a,b,c' 格式错误

Python's literal_eval says string 'a,b,c' is malformed

literal_eval 文档状态:

Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

我想解析表示元组的 unicode 字符串。为什么我得到以下输入的 ValueError: malformed string

print literal_eval(unicode('abc')) 
print literal_eval(unicode('c,d,e'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.5/ast.py", line 84, in literal_eval
    return _convert(node_or_string)
  File "/usr/lib/python3.5/ast.py", line 55, in _convert
    return tuple(map(_convert, node.elts))
  File "/usr/lib/python3.5/ast.py", line 83, in _convert
    raise ValueError('malformed node or string: ' + repr(node))
ValueError: malformed node or string: <_ast.Name object at 0x7f1da47e7860>

但是,这个例子确实有效:

print literal_eval(unicode('1,2,3'))
(1, 2, 3)

literal_eval 只解析 literals。您的字符串是变量名称的元组(abccde)。相反,您需要一个字符串元组或一个带逗号的字符串。任何一个都需要两层引号。

# string
print(literal_eval("'abc'"))
'abc'
print(literal_eval("'c,d,e'"))
'c,d,e'

# tuple of strings
print(literal_eval("'c','d','e'"))
('c', 'd', 'e')

你最后一个例子是一个整数元组,都是文字,所以它解析成功。