目录
IndexError: string index out of range
IndexError: list index out of range
IndexError: tuple index out of range
IndexError: string index out of range
指定的偏移量超过了字符串的长度。
>>> string = "China"
>>> str_sp = string[23]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
✏️规避方法:偏移量不应超过字符串的最大长度。(正向从0开始计算至字符串长度 - 1,反向从-1开始计算至字符串长度的相反数。
IndexError: list index out of range
指定的偏移量超过了列表的长度范围。
>>> demo = ["China", "Canada"]
>>> demo[3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
✏️规避方法:偏移量不应超过列表的最大长度。(正向从0开始计算至列表长度 - 1,反向从-1开始计算至列表长度的相反数)
IndexError: tuple index out of range
指定的偏移量超过了元组的长度范围。
if __name__ == '__main__':
demo_tuple = "A", "B", "C"
print(demo_tuple[3])
# IndexError: tuple index out of range
✏️规避方法:偏移量不应超过元组的最大长度。(正向从0开始计算至列表长度 - 1,反向从-1开始计算至列表长度的相反数)

本文深入探讨了Python中常见的IndexError异常,包括字符串、列表和元组的越界错误,提供了有效的规避策略,帮助开发者掌握数据结构的正确使用方法。
1909

被折叠的 条评论
为什么被折叠?



