1

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']]
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 2
    Possible duplicate of [Convert string representation of list to list](https://stackoverflow.com/questions/1894269/convert-string-representation-of-list-to-list) – jonrsharpe Apr 14 '19 at 07:36
  • 1
    But it's likely that a more effective fix would be figuring out why that's the input in the first place and using an actual serialisation format instead of just stringifying lists. – jonrsharpe Apr 14 '19 at 07:37

2 Answers2

1

How about eval if you don't need to verify the correctness of input variables:

results = [eval(x) for x in results]
andnik
  • 2,405
  • 2
  • 22
  • 33
0

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.

glhr
  • 4,439
  • 1
  • 15
  • 26