How can I loop through a string and print certain items?

后端 未结 3 594
时光说笑
时光说笑 2021-01-23 00:24
lst = \'AB[CD]EF[GH]\'

Output: [\'A\',\'B\',\'CD\',\'E\',\'F\',\'GH\']

This is what I\'ve tried but it\'s not working...

while         


        
3条回答
  •  星月不相逢
    2021-01-23 00:34

    The problems with the original code seemed to be:

    1) lst, index and multi are not initialised

    2) the loop is infinite because the loop variable (index) isn't incremented on each iteration.

    3) the close bracket needs to be skipped when detected to avoid including it in the final list

    This code is an example of how to fix those issues:

    def getList(s):
        outList=[]
        lIndex=0
        while lIndex < len(s):
            if s[lIndex] == "[":
                letters=""
                lIndex+=1
                while s[lIndex] != "]":
                    letters+=s[lIndex]
                    lIndex+=1
                outList.append(letters)
            else:
                outList.append(s[lIndex])
            lIndex+=1
        return outList
    
    print(getList('AB[CD]EF[GH]'))
    

提交回复
热议问题