import re s1="a3[b2[c1[d]]]e" def decode(string1): m = re.match("([^0-9]*)(\d)\[(.*)\]([^0-9]*)", string1) if m: return m.groups()[0] + decode(m.groups()[2]) * int(m.groups()[1]) + m.groups()[3] else: return string1 print decode(s1)