user77005
user77005

Reputation: 1849

Convert a python string in a integer list form to a proper list of integers

I have a string as [u'[15]']. I need it as a list with an int i.e. [15] I tried ast.literal_eval() But it gives the error

ValueError: malformed string

How do I fix it?

Upvotes: 3

Views: 426

Answers (2)

Anand S Kumar
Anand S Kumar

Reputation: 90889

I am getting your error, when I pass in the list , Example -

>>> a = [u'[15]']
>>> ast.literal_eval(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.6/ast.py", line 68, in literal_eval
    return _convert(node_or_string)
  File "/usr/lib64/python2.6/ast.py", line 67, in _convert
    raise ValueError('malformed string')
ValueError: malformed string

If I pass in a string like - "[u'[15]']" , I do not get any error -

>>> a = "[u'[15]']"
>>> ast.literal_eval(a)
[u'[15]']

Seems like you have a list, instead of a string, if so, you can iterate over the list and then pass in the element to ast.literal_eval , to get your element. Example -

>>> a = [u'[15]']
>>> import ast
>>> for i in a:
...     ast.literal_eval(i)
...
[15]

You can store each element in a list of its own, or if you are sure there is only one element you can also do -

>>> x = ast.literal_eval(a[0])
>>> x
[15]
>>> type(x)
<type 'list'>

Upvotes: 2

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

You have a list with a unicode string inside, you need to access the element inside the list and call literal_eval on that:

from ast import literal_eval

print literal_eval([u'[15]'][0])
[15]

You are getting an error by trying to pass the list to literal_eval not the string inside.

In [2]:  literal_eval(literal_eval([u'[15]']))
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-2-7468abfb5acf> in <module>()
----> 1 literal_eval(literal_eval([u'[15]']))

/usr/lib/python2.7/ast.pyc in literal_eval(node_or_string)
     78                 return left - right
     79         raise ValueError('malformed string')
---> 80     return _convert(node_or_string)
     81 
     82 

/usr/lib/python2.7/ast.pyc in _convert(node)
     77             else:
     78                 return left - right
---> 79         raise ValueError('malformed string')
     80     return _convert(node_or_string)
     81 

Upvotes: 2

Related Questions