1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
   | >>> txt='1[2[x]3[x[x]x][4'
>>> def delCrochets(txt):
    res          = ''
    def isThereEnd(s):
        lvl = 0
        for i,char in enumerate(txt[s:]):
            if   char == '['         : lvl += 1
            elif char == ']' and lvl : lvl -= 1
            if not lvl : return i+1
        return 0
    while 1:
        idxs = txt.find('[')
        if idxs==-1: return res+txt
        idxe = isThereEnd(idxs)
        if idxe:
            res += txt[:idxs]
            txt  = txt[idxs+idxe:]
        else :
            idxs = txt.find('[',idxs+1)
            if idxs==-1: return res+txt
            res += txt[:idxs]
            txt  = txt[idxs:]
 
>>> delCrochets(txt)
'1[23[4' | 
Partager