pythonpython-2.7evalliterals

literal_eval returns malformed string given a string without quote


I try to convert a string containing two lists using literal_eval as shown below.

from ast import literal_eval
literal_eval('[[ba], [38]]')

However I got this error

raise ValueError('malformed string')

Is it because 'ba' is not converted to string? How can I fix this?


Solution

  • It's because that's not a valid set of Python literals you're asking it to eval. The string needs to be quoted, like so:

    from ast import literal_eval
    literal_eval('[["ba"], [38]]')
    

    Then you will get the correct result:

    [['ba'], [38]]