凯撒密码奇怪的重复

时间:2014-11-18 17:19:25

标签: python encryption

好的,所以我正在制作一个Caesar Cipher程序,将字母移动+5。

这是我的代码:

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"]

phrase = input("Please enter a phrase without any punctuation")
phrase = str.upper(phrase)
phrase = phrase.replace(" ","")

for each in range(len(phrase)):
    letternum = alphabet.index(phrase[each])
    if letternum > 21:
        letternum = letternum+5-26
        phrase = phrase.replace(phrase[each],alphabet[letternum])

    else:
        letternum = letternum + 5
        phrase = phrase.replace(phrase[each],alphabet[letternum])

print("Your encrypted phrase is:",phrase)

这是我的输出:

Please enter a phrase without any punctuation: abcdefghijk
Your encrypted phrase is: PLMNOPLMNOP

为什么程序重复相同的字母,即使我输入不同的字母?另外为什么不是e和b不是等等?我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

正如@Kevin提到的那样,你覆盖了phrase,所以有些字符会被多次编码。

解决方案是在新变量中建立答案:

answer = ""
for each in range(len(phrase)):
    letternum = alphabet.index(phrase[each])
    if letternum > 21:
        letternum = letternum+5-26    
    else:
        letternum = letternum + 5
    answer += alphabet[letternum]

print "Your encrypted phrase is:", answer

使用%运算符可以更简洁地编写:

for each in range (len(phrase)):
  letternum = alphabet.index(phrase[each])
  answer += alphabet[ (letternum + 5) % 26 ]

答案 1 :(得分:0)

让我向您展示一种编写Caesar密码程序的简单方法:

import string

def main():
    key = 5
    table = str.maketrans(string.ascii_letters,
                          string.ascii_lowercase[key:] +
                          string.ascii_lowercase[:key] +
                          string.ascii_uppercase[key:] +
                          string.ascii_uppercase[:key])
    plaintext = input('Please enter a phrase: ')
    ciphertext = plaintext.translate(table)
    print('Your encrypted phrase is:', ciphertext)

if __name__ == '__main__':
    main()