I have a string in the format of
string= "['a', 'b', 'a e']['de']['a']['a']"
I want this string to get converted into a list of list as
lst= [['a', 'b', 'a e'], ['de'], ['a'], ['a']]
I have a string in the format of
string= "['a', 'b', 'a e']['de']['a']['a']"
I want this string to get converted into a list of list as
lst= [['a', 'b', 'a e'], ['de'], ['a'], ['a']]
Try this:
import ast
string = "['a', 'b', 'a e']['de']['a']['a']"
string = string.replace("]", "],")
list_ = list(ast.literal_eval(string))
print(list_)
output:
[['a', 'b', 'a e'], ['de'], ['a'], ['a']]
Keep in mind that this will fail if one of items in the list is a ]
character.
Here is a simple way -
import ast
string = "['a', 'b', 'a e']['de']['a']['a']"
[ast.literal_eval(i+']') for i in string.split(']') if len(i)>0]
[['a', 'b', 'a e'], ['de'], ['a'], ['a']]
Explanation:
string.split(']')
breaks the list by the ]
bracketi+']'
appends the ]
bracket which is now removed back for each elementlen(i)>0
makes sure that no empty lists are being consideredast.literal_eval(i+']')
converts the string to actual list.