python - python字符串索引超出范围
问题描述
我写了一个代码来检查是否是 3 位数字。是阿姆斯特朗号。
x='371'
list1=['0','1','2','3','4','5','6','7','8','9',]
s=0
L=len(x)
for i in range(0,L+1):
if (x[i]==list1[0]):
s=s+0
elif x[i]==list1[1]:
s=s+1
elif x[i]==list1[2]:
s=s+(2**3)
elif x[i]==list1[3]:
s=s+(3**3)
elif x[i]==list1[4]:
s=s+(4**3)
elif x[i]==list1[5]:
s=s+(5**3)
elif x[i]==list1[6]:
s=s+(6**3)
elif x[i]==list1[7]:
s=s+(7**3)
elif x[i]==list1[8]:
s=s+(8**3)
elif x[i]==list1[9]:
s=s+(9**3)
print(s)
错误:
Traceback (most recent call last):
File "C:\Users\prasoon\AppData\Local\Programs\Python\Python37-32\Armstrongno..py", line 7, in <module>
if (x[i]==list1[0]):
IndexError: string index out of range
预期输出:最后它应该打印出最终总和 s=371(因为 371 是 armstrong 编号。)
解决方案
你的循环范围是错误的,
为什么要迭代到 L+1?
L=len(x) # L=3
L+1 = 4 # you are trying to iterate till index 3, which doesn't exist
代替:
for i in range(0,L+1):
利用:
for i in range(0,L):
推荐阅读
- ruby - 如何在 Docker 的 Alpine 上修复 ruby-bundler 包含的并发 ruby?
- html - 如何使 nth-child 停止影响所有元素
- r - 如何有条件地将 id 值迭代到数据框
- python - 如何在使用 onnx 模型进行预测时解决运行时错误?
- javascript - Javsacript。如何操作对象数组以便将具有相同元素的元素分组?
- python - 从点往四个方向走
- c - 获得纯正弦波的困难(目前获得一个微妙的频率)
- reactjs - 如何将社交媒体图标添加到反应组件?
- database - 当应用程序在发送查询以更新记录后立即断开连接时会发生什么?
- julia - 在 Julia 中获取子数组的索引