I am looping a string in Python to append in a list the words between ";" (I know there are other ways to loop strings in Python but I want this to work):
data = "ABC;AB;AB"
data_len = len(data)
items = []
separator = ";"
i = 0
while i < data_len:
item = ''
if i == 0:
while data[i] != separator:
item += data[i]
i += 1
items.append(item)
continue
i += 1
while data[i] != separator and i < data_len:
item += data[i]
i += 1
items.append(item)
The logic seems correct to me but somehow the interpreter throws an Index out of range exception:
while data[i] != separator and i < data_len: IndexError: string index out of range
Solved:
The order of the 2nd inner while loop condition checks first the
data[i]
and theni < len
The solution is to interchange the conditions in the second loop from:
to: