繁体   English   中英

如何修复 python 中的“字符串索引超出范围”错误?

[英]How to fix'string index out of range' error in 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)

您在开始时增加 FRPOS,因此最后一个字符没有值。

试试这个,它应该工作:

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

考虑aaaah的情况。

找到“h”后,您的代码还将检查“h”后的 position 是否有“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)

干杯

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM