i have a list of strings that i would like to convert to a list of tuples. Below is 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)
与eval
不同,ast.literal_eval将仅评估文字,而不评估函数调用,因此更加安全。
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 ')]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.