python - 如何修复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)
解决方案
考虑案例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)
干杯
推荐阅读
- couchbase - 如何从 Couchbase 中的这张地图中选择和更新名称值?
- r - R:从一个向量生成所有唯一的排列
- django - 如何为超级用户禁用 Django 缓存视图?
- python - Python中的AgGrid给出空白网格
- laravel - HTML 输入类型周的 Laravel date_format 验证失败
- python - resource.getrusage 总是产生相同的结果
- kubernetes - Kubernetes Private Repo Imagepullbackoff 错误
- r - 主数据表中的另一个数据表
- java - install4j - 自动更新期间的问题,因为 install4j 尝试更新注册表项
- aws-lambda - 我的 lambda 函数需要哪些权限才能从 AWS Secrets Manager 检索密钥