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

juliomalegria
  • 24,229
  • 14
  • 73
  • 89
Aaron Phalen
  • 421
  • 2
  • 7
  • 11

3 Answers3

16

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']"
Jon-Eric
  • 16,977
  • 9
  • 65
  • 97
3

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"]'
Gareth Latty
  • 86,389
  • 17
  • 178
  • 183
0

If your have many not-quoted strings inside your sting list, you can do this:

string = '[Small, Medium, Large, X-Large]'

[s.strip() for s in string[1:-1].split(',')]

which prints this:

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

However, if you have lots of numbers in your string list and just a few strings, you can use eval and its globals parameter:

mixed_string = '[1, +2, X,0  , - 4, XX, 11.2]'

eval(mixed_string, {'X': 'X', 'XX': 'XX'})

which prints this:

[1, 2, 'X', 0, -4, 'XX', 11.2]

To have all list items as stings:

[str(s) for s in eval(mixed_string, {'X': 'X', 'XX': 'XX'})]

which prints this:

['1', '2', 'X', '0', '-4', 'XX', '11.2']
Shahrokh Bah
  • 332
  • 3
  • 5