convert a list of strings that i would like to convert to a list of tuples
i have a list of strings that i would like to convert to a list of tuples. Below is开发者_如何学JAVA an example.
['(0, "ass\'")', "(-1, '\\n print self.amount')", "(0, '\\n\\n ')"]
to be converted to.
[(0, "ass\'"), (-1, '\\n print self.amount'), (0, '\\n\\n ')]
any ideas?
[ast.literal_eval(x) for x in L]
map(ast.literal_eval, list_of_tuple_strings)
Unlike eval
, ast.literal_eval will only evaluate literals, not function calls, so it much more secure.
The function eval is what you need I think, but be careful with its use:
>>> l = ['(0, "ass\'")', "(-1, '\\n print self.amount')", "(0, '\\n\\n ')"]
>>> map(eval, l)
[(0, "ass'"), (-1, '\n print self.amount'), (0, '\n\n ')]
精彩评论