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

Python中按字符比较两字符串并统计匹配位置及解决索引越界问题

解决字符串相同位置匹配统计的索引越界问题

需求

按字符比较两个字符串,统计并打印相同位置上字符匹配的次数。例如输入soon和moon时,应输出匹配3个位置。

问题

当前代码在第二个字符串长度比第一个短时,会触发「string index out of range(字符串索引超出范围)」错误。

用户尝试的代码

a = input('Enter string')
b = input('Enter string')
i=0
count = 0

while i<len(a):
    if b[i] == a[i]:
      match = match + 1
    i = i + 1
print(match, 'positions.')

错误原因

  1. 循环终止条件只判断了i < len(a),当第二个字符串b的长度小于a时,i会超过b的最大索引,访问b[i]就会触发索引越界;
  2. 变量名不一致:初始化了count但用未定义的match累加,会导致NameError。

修复后的代码

方法一:改进while循环

a = input('Enter string: ')
b = input('Enter string: ')
i = 0
match_count = 0
# 取两个字符串长度的最小值作为循环上限
max_index = min(len(a), len(b))

while i < max_index:
    if b[i] == a[i]:
        match_count += 1
    i += 1

print(match_count, 'positions.')

方法二:更简洁的for循环写法

用range生成两个字符串共同的索引范围,或者用zip直接配对字符:

a = input('Enter string: ')
b = input('Enter string: ')
match_count = 0

# 方法2.1:用range遍历共同索引
for i in range(min(len(a), len(b))):
    if a[i] == b[i]:
        match_count += 1

# 方法2.2:用zip配对字符(zip会自动截断到较短的长度)
# match_count = sum(1 for char_a, char_b in zip(a, b) if char_a == char_b)

print(match_count, 'positions.')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 18:06:04