I have a string as follows
JavaScript
x
2
1
str = "['A', 'B', 'C'] ['D', 'E', 'F']"
2
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
JavaScript
1
3
1
parse = str.somethingfunction()
2
print (parse [0][2])
3
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:
JavaScript
1
9
1
import re
2
import ast
3
4
s = "['A', 'B', 'C'] ['D', 'E', 'F']"
5
6
tuple_ = ast.literal_eval(','.join(re.findall('[.*?]', s)))
7
8
print(tuple_[0][2])
9
Output:
JavaScript
1
2
1
C
2