Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python string list to list ast.listeral_eval

Tags:

python

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

How to fix?

like image 622
Aaron Phalen Avatar asked Dec 04 '22 04:12

Aaron Phalen


2 Answers

ast.literal_eval() only accepts strings which contain valid Python literal structures (strings, numbers, tuples, lists, dicts, booleans, and None).

This is a valid Python expression containing only those literal structures:

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

This isn't:

[Small, Medium, Large, X-Large]

Two ways to create a string that works:

string = '["Small", "Medium", "Large", "X-Large"]'
string = "['Small', 'Medium', 'Large', 'X-Large']"
like image 90
Jon-Eric Avatar answered Dec 05 '22 18:12

Jon-Eric


Your string isn't a valid list. If it's a list of strings, you need quotes.

E.g:

string = '["Small", "Medium", "Large", "X-Large"]'
like image 25
Gareth Latty Avatar answered Dec 05 '22 18:12

Gareth Latty