Dave Lee
Dave Lee

Reputation: 205

ast.literal_eval not working (python string of list to list)

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!

Upvotes: 0

Views: 7120

Answers (1)

Steve Jessop
Steve Jessop

Reputation: 279225

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.

Upvotes: 8

Related Questions