shaz
shaz

Reputation: 17

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 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?

Upvotes: 0

Views: 222

Answers (3)

PaulMcG
PaulMcG

Reputation: 63709

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.

Upvotes: 1

Emmanuel
Emmanuel

Reputation: 14209

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

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798556

[ast.literal_eval(x) for x in L]

Upvotes: 5

Related Questions