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

Python string_match函数报string index out of range错误求原因及修正

求解释string_match函数中"string index out of range"错误的原因

我在实现string_match函数时碰到了string index out of range错误,想请人帮忙分析错误产生的原因,不用直接给答案,我希望自己搞懂问题出在哪。

问题背景

函数要求:给定两个字符串a和b,返回它们在相同位置上长度为2的子串匹配的次数。比如输入"xxcaazz"和"xxbaaz"时,应该返回3,因为"xx"、"aa"、"az"这三个长度为2的子串在对应位置完全匹配。

我写的代码

def string_match(a, b):
  
  count = 0
  
  if len(a) or len(b) == 0:
    return count
  
  else:
  
    if len(a) > len(b):
      for n in range(len(a)-2):
        if a[n]==b[n]:
          count +=1
          
    else:
      for n in range(len(b)-2):
        if b[n]==a[n]:
          count+=1
          
    return count

错误情况

我原本想通过索引位置对比两个字符串的字符,但运行代码时触发了string index out of range索引越界错误。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 18:55:32