首页 > 解决方案 > 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 编号。)

标签: pythonstring

解决方案


你的循环范围是错误的,

为什么要迭代到 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):

推荐阅读