While-loop - IndexError: list assignment index out of range

While-loop - IndexError: list assignment index out of range

当我尝试将 while 循环与列表结合使用时,我不断收到索引错误。

我前段时间写了代码,回来看它,但我的脑子里想不出来我的错误。显然,该错误与我的列表索引太小或太大有关。

indexes = []
#Or indexes[0], but this threw another error
indexes.append(decoded.find(special_string))

x=1
while indexes[x-1] > 0:
    total = sum(indexes)
    indexes[x] = decoded.find(special_string, total)
    x+=1

print(indexes)

我的目标是找到字符串中的所有子字符串 (special_string) 并获取它们的索引(如果您知道更简单的方法,请告诉我)。我想将所有索引写入列表以供进一步使用。

我认为您需要做的唯一更改来自:

indexes[x] = decoded.find(special_string, total) 至:

indexes.append(decoded.find(special_string, total))

您无法分配索引[x],因为它不存在。