簡體   English   中英

Python while 循環字符串索引超出范圍

[英]Python while loop string index out of range

我正在將 Python 中的字符串循環到 append 列表中的“;”之間的單詞 (我知道還有其他方法可以在 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)

邏輯對我來說似乎是正確的,但是解釋器以某種方式拋出了 Index out of range 異常:

while data[i]:= separator and i < data_len: IndexError: string index out of range

解決了:

第二個內部 while 循環條件的順序首先檢查data[i]然后i < len

解決方案是交換第二個循環中的條件:

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

至:

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

啟動最后一個while循環只是一個小錯誤。 必須交換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