3

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?

4
  • That seems like a list, are you sure, you do not have a list? Commented Aug 4, 2015 at 15:17
  • <type 'list'> when I print type(value). where value=[u'[15]'] Commented Aug 4, 2015 at 15:21
  • oh I understood the problem I should do ast.literal_eval(value[0]). Is that correct? Commented Aug 4, 2015 at 15:23
  • @user77005, yes, you cannot call literal_eval on a list Commented Aug 4, 2015 at 15:25

2 Answers 2

2

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 
Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

For the final code snippet you have, what is type(x)?
It is list . Added that to answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.