>>> 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?
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']"
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"]'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With