darkpirate darkpirate - 22 days ago 6
Python Question

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

documentation states:


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.


I want to parse a unicode string representing a tuple. Why do I get
ValueError: malformed string
for the following inputs?

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>


However, this example does work:

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

Answer

literal_eval only parses literals. Your string is a tuple of variable names (abc, c, d, e). Instead, you want either a tuple of strings or a string with commas. Either one requires two levels of quotes.

# 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')

Your last example is a tuple of ints, which are all literals, so it parses successfully.