IndexError:列表索引超出凯撒密码

时间:2016-04-06 16:34:34

标签: python python-2.7 encryption caesar-cipher

我正在制作一个Caesar密码,当我运行代码时,我得到一个索引错误。当它是几个字母时,它可以对消息进行加密和加密,但当我输入十个以上的单词时,它会给我一个索引错误。

shift_key = int(raw_input("Enter in your key shift: 1-9\n>>> "))

alphabet = ['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']
encrypted_alphabet = []
encrypted_message = ''

for i in alphabet[shift_key:]:
    encrypted_alphabet.append(i)

input = raw_input("Enter text to be decoded\n>>> ").upper()
input = input.split()

for i in input:
    for j in i:
        index = alphabet.index(j)
        encrypted_message += encrypted_alphabet[index]
    encrypted_message += ' '
print encrypted_message  

1 个答案:

答案 0 :(得分:2)

问题在于以下两行:

for i in alphabet[shift_key:]:
    encrypted_alphabet.append(i)

请注意,执行alphabet[shift_key:] 切片列表alphabet只能从shift_key开始采用这些元素。

换句话说,如果shift_key为25,那么alphabet[shift_key:]只返回['Y','Z']。由于您将这些内容附加到encrypted_alphabetencrypted_alphabet然后变为['Y','Z']。但你想要的还是附加在encrypted_alphabet末尾的字母 rest

简单地说,encrypted_alphabetalphabet不匹配的长度

你可以通过

简单地纠正它
for i in alphabet[shift_key:] + alphabet[:shift_key]:
    encrypted_alphabet.append(i)

或(甚至更简单)

encrypted_alphabet = alphabet[shift_key:] + alphabet[:shift_key]

但是,如果您想知道正确的方式,请使用内置字符串方法maketrans,这更简单:

import string

shift_key = int(raw_input("Enter in your key shift: 1-9\n>>> "))

alphabet = string.ascii_uppercase
encrypted_alphabet = alphabet[shift_key:] + alphabet[:shift_key]
caesar = string.maketrans(alphabet,encrypted_alphabet)
input = raw_input("Enter text to be decoded\n>>> ").upper()

print(input.translate(caesar))

快速解释

如代码所示,maketrans在两个字符串之间创建转换表,将第一个字符映射到另一个字符串。然后,您可以将此转换表提供给每个字符串所具有的.translate()方法。