I want a Python function that takes a string, and returns an array, where each item in the array is either a character, or another array of this kind. Nested arrays are mark
Using regex and ast.literal_eval
>>> import re
>>> from ast import literal_eval
>>> def listit(t):
... return list(map(listit, t)) if isinstance(t, (list, tuple)) else t
...
def solve(strs):
s = re.sub(r'[A-Za-z]', "'\g<0>',", strs)
s = re.sub(r"\)", "\g<0>,", s)
try: return listit( literal_eval('[' + s + ']') )
except : return "Invalid string! "
...
>>> solve("abc")
['a', 'b', 'c']
>>> solve("a(b)c")
['a', ['b'], 'c']
>>> solve("a(b(c))")
['a', ['b', ['c']]]
>>> solve("a(b(c)")
'Invalid string! '
>>> solve("a)b(c")
'Invalid string! '
>>> solve("a(b))c")
'Invalid string! '
>>> solve('a((b(c))d)(e)')
['a', [['b', ['c']], 'd'], ['e']]