简体   繁体   English

Python while 循环字符串索引超出范围

[英]Python while loop string index out of range

I am looping a string in Python to append in a list the words between ";"我正在将 Python 中的字符串循环到 append 列表中的“;”之间的单词(I know there are other ways to loop strings in Python but I want this to work): (我知道还有其他方法可以在 Python 中循环字符串,但我希望它能够工作):

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:逻辑对我来说似乎是正确的,但是解释器以某种方式抛出了 Index out of range 异常:

while data[i]:= separator and i < data_len: IndexError: string index out of range 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 then i < len第二个内部 while 循环条件的顺序首先检查data[i]然后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:

It was just a small mistake when last while loop was initiated.启动最后一个while循环只是一个小错误。 The data[i] != separator and i < data_len conditions must be swapped.必须交换data[i] != separator and i < data_len条件。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM