Skip to content
Advertisement

how to analysis String contain multiple list in python

I have a string as follows

str = "['A', 'B', 'C'] ['D', 'E', 'F']"

I use json.load with ast.literal_eval neither works

Is there any function that can quickly and perfectly parse this string?

hope through like

parse = str.somethingfunction()
print (parse [0][2])

output: C

Advertisement

Answer

The string does not represent a valid Python construct. Therefore, neither eval nor ast.literal_eval will be able to parse it. However, it appears that all you need to do is insert a comma in the appropriate position. You could do it like this:

import re
import ast

s = "['A', 'B', 'C'] ['D', 'E', 'F']"

tuple_ = ast.literal_eval(','.join(re.findall('[.*?]', s)))

print(tuple_[0][2])

Output:

C
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement