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

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

    You can't use

    lst += multi
    

    because you can't concatenate a string with a list.

    Moreover, your code enters an infinite loop, because you aren't updating the curr_char variable inside the inner loop, so the condition will always be True.

    Also, you are not handling the case when curr_char != '['. And more errors there are.

    You can use this code which fixes the above errors while using the same basic logic as your code:

    index = 0
    multi = ""
    res = []
    my_str = 'AB[CD]EF[GH]'
    
    while (index < len(my_str)):
        curr_char = my_str[index]
        if curr_char == '[':
            multi += curr_char
            while curr_char != ']':
                index += 1
                curr_char = my_str[index]
                multi += curr_char
            res.append(multi)
            multi = ""
        else:
            res.append(curr_char)
        index += 1
    
    print(res)
    

    Output:

    ['A', 'B', '[CD]', 'E', 'F', '[GH]']
    

提交回复
热议问题