Albert
Albert

Reputation: 3651

Python convert formatted string to list

I have a string "[u'foo']" (Yes, it includes the square brackets and the u''). I have to convert that to a list which looks like [u'foo'].

list("[u'foo']") won't work.

Any suggestions?

Upvotes: 1

Views: 2260

Answers (2)

leoluk
leoluk

Reputation: 12981

eval("[u'foo']", {'__builtins__':[]}, {})

Upvotes: 1

mechanical_meat
mechanical_meat

Reputation: 169524

>>> import ast
>>> s = "[u'foo']"
>>> ast.literal_eval(s)
[u'foo']

documentation

Upvotes: 18

Related Questions