Reputation:
In Python, I want to convert all strings in a list to non-string.
So if I have:
results = ["['new','york','intrepid', 'bumbling']","['duo', 'deliver', 'good', 'one']"]
How do I make it:
results = [['new','york','intrepid', 'bumbling'],['duo', 'deliver', 'good', 'one']]
Upvotes: 1
Views: 1502
Reputation: 4547
Using literal_eval()
from ast
is much safer than eval()
:
import ast
results = ["['new','york','intrepid', 'bumbling']","['duo', 'deliver', 'good', 'one']"]
results_parsed = [ast.literal_eval(x) for x in results]
print(results_parsed)
Output:
[['new', 'york', 'intrepid', 'bumbling'], ['duo', 'deliver', 'good', 'one']]
ast.literal_eval()
only parses strings containing a literal structure (strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None), not arbitrary Python expressions.
Upvotes: 0
Reputation: 2804
How about eval
if you don't need to verify the correctness of input variables:
results = [eval(x) for x in results]
Upvotes: 1