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

为何两段相似Python代码一段报IndexError: string index out of range?

IndexError: string index out of range 报错原因分析

核心问题

报错代码在修改字符串s后未终止当前的for循环,导致后续循环仍使用初始的索引范围,但此时s已经被缩短,进而触发索引越界。

具体触发过程(以输入abBAcC为例)

  1. 初始s长度为6,for循环基于range(len(s)-1)生成索引序列:0、1、2、3、4。
  2. 当index=1时,s[1]='b'和s[2]='B'匹配,执行s = s.replace(s[1:3], ''),此时s变为aAcC(长度从6变为4)。
  3. 报错代码未终止for循环,继续执行后续索引:index=2、index=3、index=4。
  4. 当index=4时,当前s的最大有效索引是3(长度为4),访问s[4]直接触发IndexError: string index out of range。

和正常代码的关键差异

报错代码正常代码
修改s后继续执行for循环,沿用初始索引范围修改s后立即break退出for循环,回到while开头重新计算索引范围
使用str.replace()替换所有匹配的子串(可能误删非相邻的目标对)使用切片s[:i] + s[i+2:]精准删除当前位置的一对相邻字符

修正方案

调整报错代码逻辑,和正常代码保持一致:修改s后立即终止当前for循环,同时用切片替换replace精准删除目标子串:

class Solution:
    def makeGood(self, s: str) -> str:
        while len(s) > 1:
            find = False
            for index in range(len(s) - 1):
                if abs(ord(s[index]) - ord(s[index + 1])) == 32:
                    # 用切片精准删除当前相邻对
                    s = s[:index] + s[index + 2:]
                    find = True
                    # 修改后立即退出for循环,回到while重新扫描
                    break
            
            if not find:
                break

        return s

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 01:25:40