我正在尝试制作凯撒密码,但我遇到了问题。
它工作得很好,但我想在输入的单词中添加空格。如果您输入的句子中包含空格。它只是打印出=而不是加密时的空格。谁能帮我解决这个问题,以便打印出空格?
这是我的代码:
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')
你需要仔细看看你的条件:
给定一个空间,ord(letter) + shift
将在 shifted
中存储 32+ shift
(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
...
只需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 ("")
这里有一个活生生的例子