Converting python string as integer list to correct list of integers

I have a string like [u'[15]']

. I need it as a list with int ie [15]

I tried ast.literal_eval()

But it gives error

ValueError: malformed string

      

How to fix it?

+3


source to share


2 answers


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

from ast import literal_eval

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

      



You are getting an error trying to pass a literal_eval list and not a 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 

      

+2


source


I am getting your error when I go to 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 don't get any error -

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

      



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

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

      

You can keep each item in its own list, or if you are sure there is only one item you can also do -

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

      

+2


source







All Articles