为什么为什么不断出现错误“ IndexError:列表索引超出范围”?

时间:2020-11-12 04:27:23

标签: python

当我不相信自己越界时,我不明白为什么会出现此错误。错误似乎在x = lowercase[i + self.num]

class Cipher:
        def __init__(self, string, num):
            self.string = string
            self.num = num
    
    def encrypt(self):
        lowercase = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
                     'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
        uppercase = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N'
                     'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
        # establish the array from the inputed string
        split = []
        for x in range(len(self.string)):
            split.append(self.string[x])

        for x in split:
            for i in range(len(lowercase)):
                if (x == lowercase[i]):
                    x = lowercase[i + self.num]
                    print(x)


test = Cipher("hello", 1)
test.encrypt()

2 个答案:

答案 0 :(得分:3)

Z(或z)之后没有字母。您必须指定“下一个”字母,通常为A(和a)。因此,[i + self.num]必须为[(i + self.num) % len(lowercase)]。模运算符将搜索换行。

答案 1 :(得分:1)

x = lowercase[i + self.num]提高了索引如果i=25 and self.num=2会出错,所以您应该使用x = lowercase[(i + self.num)%26]

此外,如果要将字符串转换为列表,则split = list(self.string)是更好的方法。