首页 > 解决方案 > 如何修复python中的“字符串索引超出范围”错误?

问题描述

我试图制作一个程序,用某些数字替换字母或字母组,但程序返回'IndexError:字符串索引超出范围'。这是什么原因造成的?

phr = input('Frase: ')
phr=phr.lower()
out = ''
for pos in range(len(phr)):
    frpos=pos+1
    if phr[pos]=='h'and phr[frpos]=='e':
        out+='1'
    if phr[pos]=='h':
        out+='2'
print(out)

标签: python

解决方案


考虑案例aaaah

找到“h”后,您的代码还将检查“h”之后的位置是否有“e”。这种情况是导致您的程序中断的原因。为了解决这个问题,一个简单的解决方法是检查“frpos”是否有效,如下所示:

phr = input('Frase: ')
phr=phr.lower()
out = ''
for pos in range(len(phr)):
    frpos=pos+1
    if phr[pos]=='h'and frpos<len(phr) and phr[frpos]=='e':
        out+='1'
    if phr[pos]=='h':
        out+='2'
print(out)

干杯


推荐阅读