Python Caesar密码ascii添加空格

时间:2017-11-08 09:57:17

标签: python ascii

我试图制作凯撒密码并且我遇到了问题。

它完美地工作但我希望在输入的单词中添加空格。如果输入带有空格的句子。它只是在加密时输出=而不是空格。任何人都可以帮我解决这个问题,以便打印出空格吗?

这是我的代码:

word = input("What is the message you want to encrypt or decrypt :")
def circularShift(text, shift):
    text = text.upper()
    cipher = "Cipher = "
    for letter in text:
        shifted = ord(letter) + shift
        if shifted < 65:
            shifted += 26
        if shifted > 90:
            shifted -= 26
        cipher += chr(shifted)
        if text == (" "):
            print(" ")
    return cipher
print (word)
print ("The encoded and decoded message is:")
print ("")
print ("Encoded message  = ")
print (circularShift(word , 3))
print ("Decoded message  = ")
print (circularShift(word , -3))
print ("")
input('Press ENTER to exit')

2 个答案:

答案 0 :(得分:5)

你需要仔细研究你的情况:

给定空格,ord(letter) + shift会在shift中存储32 + shiftedshift为3时为35)。那是&lt; 65,因此添加了26,在这种情况下导致61,而编号为61的字符恰好是=

要解决此问题,请确保只触及string.ascii_letters中的字符,例如作为循环中的第一个语句:

import string

...
for letter in text:
    if letter not in string.ascii_letters:
        cipher += letter
        continue
...

答案 1 :(得分:2)

只需split内容:

print (word)
print ("The encoded and decoded message is:")
print ("")
print ("Encoded message  = ")
encoded = " ".join(map(lambda x: circularShift(x, 3), word.split()))
print (encoded)
print ("Decoded message  = ")
encoded = " ".join(map(lambda x: circularShift(x, -3), encoded.split()))
print (encoded)
print ("")

这里有live example

相关问题