0

I am trying to convert the following string of a list back to a list.

[('zX7XjZ1Vwai5UbqNDDJ1NQ', 570512, [155])] 

I have tried both eval() and ast.literal_eval but for some reason when I print the type of my converted string it is still a string (but with the quotations removed)

I have also tried using json.loads()

It seems like no matter how hard I try, I cannot convert this string of a list to a python list!

5
  • eval worked for me. what version of python do you have? Commented May 7, 2015 at 11:57
  • That is not a string of a list but a list with one tuple element that contains string and int and list. Commented May 7, 2015 at 11:58
  • Cannot reproduce, ast.literal_eval("[('zX7XjZ1Vwai5UbqNDDJ1NQ', 570512, [155])]") == [('zX7XjZ1Vwai5UbqNDDJ1NQ', 570512, [155])] returns True. Commented May 7, 2015 at 11:59
  • eval("[('zX7XjZ1Vwai5UbqNDDJ1NQ', 570512, [155])]") gives [('zX7XjZ1Vwai5UbqNDDJ1NQ', 570512, [155])] Commented May 7, 2015 at 11:59
  • Did you try type on result? Commented May 7, 2015 at 11:59

1 Answer 1

8

You probably have an additional set of quotation marks, not shown in the question, included in the literal you're evaluating:

[('zX7XjZ1Vwai5UbqNDDJ1NQ', 570512, [155])] 

is a list, whereas:

"[('zX7XjZ1Vwai5UbqNDDJ1NQ', 570512, [155])]" 

is a string.

Therefore,

ast.literal_eval("[('zX7XjZ1Vwai5UbqNDDJ1NQ', 570512, [155])]") 

returns a list, whereas:

ast.literal_eval('''"[('zX7XjZ1Vwai5UbqNDDJ1NQ', 570512, [155])]"''') 

returns a string. The nested quotes have become verbose in these examples written as Python source code, but perhaps you've read "[('zX7XjZ1Vwai5UbqNDDJ1NQ', 570512, [155])]" from a file.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.