-1

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']]

2 Answers2

0

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.

sarartur
  • 1,178
  • 1
  • 4
  • 13
0

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:

  1. string.split(']') breaks the list by the ] bracket
  2. i+']' appends the ] bracket which is now removed back for each element
  3. len(i)>0 makes sure that no empty lists are being considered
  4. ast.literal_eval(i+']') converts the string to actual list.
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51