Eduardo G
Eduardo G

Reputation: 440

Python while loop string index out of range

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

Upvotes: 1

Views: 501

Answers (2)

Eduardo G
Eduardo G

Reputation: 440

Solved:

The order of the 2nd inner while loop condition checks first the data[i] and then i < len

The solution is to interchange the conditions in the second loop from:

while data[i] != separator and i < data_len:

to:

while i < data_len and data[i] != separator:

Upvotes: 1

odd_wolf
odd_wolf

Reputation: 53

It was just a small mistake when last while loop was initiated. The data[i] != separator and i < data_lenconditions must be swapped.

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)
        #print(items)
        continue
    i += 1
    #print(i)
    while i < data_len and data[i] != separator:
        item += data[i]
        i += 1
                    
    items.append(item)
    #print(items)

Upvotes: 0

Related Questions