1

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
3
  • 1
    Can you clarify? What's the list supposed to contain? Commented 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. Commented 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? Commented Sep 2, 2010 at 0:15

2 Answers 2

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

documentation

answered Sep 1, 2010 at 22:47
Sign up to request clarification or add additional context in comments.

Comments

1
eval("[u'foo']", {'__builtins__':[]}, {})
answered Sep 1, 2010 at 22:46

6 Comments

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.
POC: eval('__import__("os").getcwd()', {}, {}), I edited my answer
@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.
@Aaron, cool... By the way, if I can't use literal_eval(), what would you suggest as a 'secure' eval?
@Albert, I would suggest modifying your desires so that you don't have to.
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.