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?
John Kugelman
365k70 gold badges555 silver badges600 bronze badges
asked Sep 1, 2010 at 22:44
Albert
3,6513 gold badges31 silver badges54 bronze badges
-
1Can you clarify? What's the list supposed to contain?Mike– Mike2010年09月01日 22:46:42 +00:00Commented Sep 1, 2010 at 22:46
-
Where does the string come from? That's not a very useful format to have; if you're generating it, consider using a better format.habnabit– habnabit2010年09月01日 23:16:37 +00:00Commented Sep 1, 2010 at 23:16
-
I get it from GAE bulkloader bulk_download. It's a list property in the datastore. It get's downloaded and ends up looking like that in my csv file. Any suggestions?Albert– Albert2010年09月02日 00:15:36 +00:00Commented Sep 2, 2010 at 0:15
2 Answers 2
>>> import ast
>>> s = "[u'foo']"
>>> ast.literal_eval(s)
[u'foo']
answered Sep 1, 2010 at 22:47
mechanical_meat
170k25 gold badges238 silver badges231 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
eval("[u'foo']", {'__builtins__':[]}, {})
answered Sep 1, 2010 at 22:46
leoluk
13k6 gold badges47 silver badges51 bronze badges
6 Comments
habnabit
You know that passing empty dicts for
locals and globals isn't enough to 'secure' eval, yes? This still gives an attacker basically full access to your system.leoluk
POC:
eval('__import__("os").getcwd()', {}, {}), I edited my answerhabnabit
@leoluk, that doesn't 'prove' anything.
eval("[x for x in type(type(1)).__bases__[0].__subclasses__() if x.__name__ == 'file'][0]('/etc/passwd').readline()", {}, {}) gives me the first line of /etc/passwd on my system.Albert
@Aaron, cool... By the way, if I can't use literal_eval(), what would you suggest as a 'secure' eval?
habnabit
@Albert, I would suggest modifying your desires so that you don't have to.
|
lang-py