You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python字符串反转程序触发IndexError: string index out of range错误求助

Python字符串反转程序触发IndexError: string index out of range错误求助

嘿,我来帮你排查这个索引越界的问题!先搞清楚报错的根源:

Python里字符串的索引是从0开始的,比如一个长度为5的字符串,它的有效索引范围是0到4(也就是len(word)-1)。你看代码里报错的这一行:

out +=(word[length - i])

第一次进入循环时,i的值是0,这时候length - i就等于length,而这个索引在字符串里是不存在的——因为最大的有效索引是length-1,这就直接触发了索引越界的错误。

修正你的循环代码

只需要把索引调整一下,改成length - i - 1就可以了,这样第一次循环就能取到最后一个字符,直到循环结束取到第一个字符:

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))  # 优化输出:把列表转成字符串更美观

如果你之前换for循环也没解决,大概率是没改对索引逻辑,比如用for循环的话可以这么写:

word = input("type a thingy: ")
out = []
for idx in range(len(word)-1, -1, -1):
    out.append(word[idx])
print(''.join(out))

更简洁的Python式写法

其实Python里反转字符串有超级简便的方法,完全不用手动写循环,直接用切片语法[::-1]就行,一行代码搞定:

word = input("type a thingy: ")
print(word[::-1])

这个切片的意思是“从字符串末尾开始,以步长-1倒序遍历整个字符串”,既简洁又不容易出错~

备注:内容来源于stack exchange,提问作者emotts

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 17:29:32