
本文详解python中“indexerror: string index out of range”错误的典型成因——字符串索引从0开始、最大有效索引为len(s)-1,通过反转字符串的实例说明如何定位并修正越界访问。
本文详解python中“indexerror: string index out of range”错误的典型成因——字符串索引从0开始、最大有效索引为len(s)-1,通过反转字符串的实例说明如何定位并修正越界访问。
在Python中,字符串是基于0索引(zero-based) 的序列类型:对于任意非空字符串 s,其合法索引范围严格限定为 0, 1, 2, ..., len(s)-1。超出该范围(如使用 s[len(s)] 或 s[-len(s)-1] 以外的负索引)将立即触发 IndexError: string index out of range。
以提问中的代码为例:
word = input("type a thingy: ")
length = len(word)
i = 0
out = []
while i < length:
out += (word[length - i]) # ❌ 错误:第一次循环时 i=0 → 索引为 length,越界!
i += 1
print(str(out))问题核心在于第5行:word[length - i]。当 i = 0 时,表达式计算为 word[length] —— 而字符串最后一个字符的索引是 length - 1,因此 length 已超出右边界(相当于访问第 length+1 个位置),必然报错。
✅ 正确做法是将索引偏移调整为 length - i - 1,确保首轮访问末尾字符:
立即学习“Python免费学习笔记(深入)”;
word = input("type a thingy: ")
length = len(word)
i = 0
out = []
while i < length:
out += word[length - i - 1] # ✅ 修正:-1 补偿零起点偏移
i += 1
print(''.join(out)) # 更推荐用 join 替代 str(out),避免输出 ['h','e','l','l','o'] 这类格式⚠️ 注意事项:
-
out += word[...]实际调用的是列表的__iadd__,等价于out.extend([char]);若想追加单个字符,也可写为out.append(word[...]),语义更清晰; - Python中更简洁、地道的字符串反转方式是切片:
reversed_word = word[::-1]; - 使用
for循环可天然规避索引计算错误,例如:out = [] for char in reversed(word): out.append(char) print(''.join(out))
总结:字符串索引越界本质是逻辑偏移未对齐零起点规则。调试时牢记 s[i] 合法 ⇔ 0 ≤ i ,并在涉及 <code>len(s) - i 类表达式时主动检查是否遗漏 -1 补偿。养成用切片或内置函数(如 reversed())替代手动索引的习惯,能显著提升代码健壮性与可读性。


















