1

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

2
  • Because you increment i but still use afterwards and it causes an out of index error. Check your formatting because python indentation affects logic. Commented Apr 24, 2021 at 11:33
  • 1
    Use while i < data_len and data[i] != separator: rather than while data[i] != separator and i < data_len: (i.e. check that index is in range before using it). Commented Apr 24, 2021 at 11:35

2 Answers 2

1

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:
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.