lst = \'AB[CD]EF[GH]\'
Output: [\'A\',\'B\',\'CD\',\'E\',\'F\',\'GH\']
This is what I\'ve tried but it\'s not working...
while
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]']