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

后端 未结 3 585
时光说笑
时光说笑 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:36

    Please try the following code snippet.

    my_string = 'AB[CD]EF[GH]'
    
    lst = []
    ind = 0
    n = len(my_string)
    
    while (ind < n):
        if my_string[ind] == '[':
            # if '[' is found, look for the next ']' but ind should not exceed n.
            # Your code does not do a ind < n check. It may enter an infinite loop.
            ind += 1 # this is done to skip the '[' in result list
            temp = '' # create a temporary string to store chars inside '[]'
            while ind < n and my_string[ind] != ']':
                temp = temp + my_string[ind]
                ind+=1
            lst.append(temp) # add this temp string to list
            ind += 1 # do this to skip the ending ']'.
        else:
            # If its not '[', simply append char to list.
            lst.append(my_string[ind])
            ind += 1
    
    print(lst)
    

提交回复
热议问题