开发者

convert a list of strings that i would like to convert to a list of tuples

开发者 https://www.devze.com 2023-02-15 16:55 出处:网络
i have a list of strings that i would like to convert to a list of tuples. Below is开发者_如何学JAVA an example.

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  ')]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号