I want to parse a string with nested brackets into a nested list.
Example - parse_nested("abc(def(gh)ij)klm") -> ["abc", ["def", ["gh"], "ij"], "klm"]
.
My code works, but I was wondering if there was better way of doing this.
Here my code (I will write checks to catch malformed input later):
def match(s, start, stop):
start = c = s.index(start)
level = 0
while c < len(s):
if s[c] == start:
level += 1
elif s[c] == stop:
level -= 1
if level == 0:
return (start+1, c)
c += 1
return None
def parse_nested(s):
if start not in s and stop not in s:
return s
else:
g = match(s, start, stop)
first = s[:g[0]-1]
middle = parse_nested(s[g[0]:g[1]])
last = parse_nested(s[g[1]+1:])
result = [first] if first else []
if type(middle) == str:
result.append([middle])
else:
result.append(middle)
if last:
if type(last) == str:
result.append(last)
else:
result += last
return result
Short of using a parsing library, is there any much shorter/better way of doing this?