0

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

Alexander
  • 16,091
  • 5
  • 13
  • 29
rookie
  • 41
  • 5

1 Answers1

3

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
DarkKnight
  • 19,739
  • 3
  • 6
  • 22