为什么这会显示"string index out of range sometimes"?



我每次都使用不同长度的 father[0] 值在循环中运行此代码。一切正常,但有时它会弹出错误"字符串索引超出范围">

for a in range(len(father[0])):
column = [item[a] for item in father]

只需在跳入循环之前为空字符串设置一个检查器即可。请注意空字符串,因为它们可能会引发您当前面临的异常。

>>> empty_string = ''
>>> empty_string[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range

你可能想看看,你传递给父亲[0]的值是什么,正如上面@Devrim提到的,可能是字符串为空。

相关内容

最新更新