繁体   English   中英

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

[英]Why do I keep getting the error "IndexError: list index out of range"?

我不明白为什么当我不相信我正在循环出界时会收到此错误。 错误似乎在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()

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

x = lowercase[i + self.num] raised index Error if i=25 and self.num=2 ,所以你应该使用x = lowercase[(i + self.num)%26]

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

暂无
暂无

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

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