Python凯撒密码ASCII加空格

3

我正在尝试制作凯撒密码,但是遇到了问题。

它的运行非常完美,但是我想在输入的单词中添加空格。如果您输入带有空格的句子,则加密时只会打印出=而不是空格。有谁能帮我修复这个问题,以便它能够打印出空格?

这是我的代码:

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个回答

5
你需要仔细查看你的条件:
给定一个空格,ord(letter) + shift 会将32+shift存储在shifted中(当shift为3时为35)。这是小于65的,因此会添加26,在这种情况下导致61,并且数字为61的字符恰好是=
要修复这个问题,请确保只触及在string.ascii_letters中的字符,例如作为您循环中的第一条语句。
import string

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

我喜欢 string.ascii_letters,我不知道它在那里 :D。 - Netwave

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 ("")

Here you have a live example


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接