
本文详解python字符串反转时常见的“indexerror: string index out of range”错误成因与修复方法,通过修正索引逻辑、提供多种安全实现方式,并强调python索引从0开始、最大有效索引为len(s)-1的核心规则。
本文详解python字符串反转时常见的“indexerror: string index out of range”错误成因与修复方法,通过修正索引逻辑、提供多种安全实现方式,并强调python索引从0开始、最大有效索引为len(s)-1的核心规则。
在您提供的代码中,报错源于对Python字符串索引机制的误解。Python中字符串是零基索引(zero-based):对于长度为 n 的字符串 word,合法索引范围是 0 到 n-1(含)。而原代码中:
out += (word[length - i])
当 i = 0 时,length - i 等于 length,即尝试访问 word[len(word)] —— 这已超出末尾位置(最后一个字符索引是 len(word) - 1),因此触发 IndexError。
✅ 正确做法是将索引调整为 length - i - 1,确保首轮取到末字符:
word = input("type a thingy: ")
length = len(word)
i = 0
out = []
while i <blockquote><p>? 注意:<code>out += word[...]</code> 实际调用的是列表的 <code>__iadd__</code>,等价于 <code>out.extend([char])</code>;若直接写 <code>out += 'abc'</code>(字符串),会逐字符扩展——此处合理,但需确保右侧是单字符。同时,<code>str(out)</code> 会输出类似 <code>['o', 'l', 'l', 'e', 'h']</code> 的字符串表示,而非 <code>'olleh'</code>;使用 <code>''.join(out)</code> 才能得到预期的拼接结果。</p></blockquote><p>? 更简洁、Pythonic 的替代方案(推荐初学者掌握):</p>
-
切片法(最常用):
word = input("type a thingy: ") reversed_word = word[::-1] print(reversed_word) -
reversed() + join:
word = input("type a thingy: ") reversed_word = ''.join(reversed(word)) print(reversed_word) -
for 循环正向遍历(避免索引计算):
word = input("type a thingy: ") out = [] for char in word: out.insert(0, char) # 头插法(效率略低,仅作演示) print(''.join(out))
? 关键总结:
- 字符串索引永远从
0开始,最大合法索引 =len(s) - 1; - 使用
s[i]前务必验证0 ≤ i ; - 优先选用内置机制(如切片
[::-1])而非手动索引,既安全又高效; - 调试索引类错误时,可在循环中打印
i和length - i - 1辅助验证。
掌握这一底层索引规则,将帮助您规避大量类似边界错误,夯实Python编程基础。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!











