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

编写字符串倒序打印程序时遇string index out of range错误求助

问题分析与解决

错误原因

你的代码逻辑存在两个核心问题:

  1. 遍历方向与起始索引错误:你要实现从末尾倒序打印,但初始index设为0(字符串第一个字符的索引),每次还往负数方向递减,等于从第一个字符开始往“字符串范围外”遍历,完全偏离目标。
  2. 循环条件失效:index < len(string)这个条件永远成立——因为index会变成负数,必然小于正的字符串长度,导致循环无限执行,直到index小到超出字符串的负索引范围(比如字符串长度为3时,index到-4,string[-4]不存在),触发string index out of range错误。

修复方案

方案1:修正while循环逻辑

调整起始索引和循环条件,让索引从最后一个字符开始,递减到0:

string = input("Please type in a string: ")  # input返回的本身就是字符串,无需str()转换
index = len(string) - 1  # 定位到最后一个字符的索引
while index >= 0:
    print(string[index])
    index -= 1  # 等价于index += -1,写法更直观

方案2:Pythonic简化写法

直接用字符串切片或reversed函数实现倒序,代码更简洁:

# 方法A:切片生成倒序字符串,逐个打印
string = input("Please type in a string: ")
for char in string[::-1]:
    print(char)

# 方法B:用reversed获取倒序迭代器,拼接后一次性打印
string = input("Please type in a string: ")
print(''.join(reversed(string)))

内容的提问来源于stack exchange,提问作者Amin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 00:12:37