每当我输入编码“hello world”的移位量为1时,就会得到“ifmmp xpsme1”,这是正确的。然而,每当我试图解码它,它给我“hello9worldJ”这显然是不正确的。你知道吗
def encryption(string, shift):
cipher = ''
for char in string:
if char == ' ':
cipher = cipher + char
elif char.isupper():
cipher = cipher + chr((ord(char) + shift - 65) % 26 + 65)
else:
cipher = cipher + chr((ord(char) + shift - 97) % 26 + 97)
shift = str(shift)
return cipher + shift
def cipherDecrypt(word, key):
decryptString = ""
for i in word:
charvalue = ord(i) - key
if charvalue < 97:
charvalue = ord("z") - (96-charvalue)
decryptString += chr(charvalue)
elif charvalue == 32:
decryptString += " "
else:
decryptString += chr(charvalue)
return decryptString
def main():
decision = ""
while decision != "stop":
decision = input("Would you like to 'encode' or 'decode' or 'stop': ")
if decision == "encode":
text = input("Enter a string to encode: ")
num = int(input("Enter your number to shift: "))
print("Original input: ", text)
print("After encryption: ", encryption(text, num))
elif decision == "decode":
text = input("Enter a string to decode: ")
num = int(input("Enter your number to shift: "))
print("Original input: ", text)
print("After encryption: ", cipherDecrypt(text, num))
main()
出现这个问题的原因是,当您到达“
(ord(" ") == 32)
”时,if条件得到满足,因此您得到的是9而不是空格。你知道吗一个非常简单的解决方案: 将if改为:
if charvalue < 97 and charvalue != ord(" ") - key:
和elif to:
elif charvalue == ord(" ") - key
之所以使用
- key
部分,是因为在循环中将charvalue设置为ord(i) - key
。在减去键之后,您需要检查每个大小写,这意味着在您的情况下,如果charvalue == 31
(32-1),您应该检查空格在你做的时候
您已经将charvalue设置为
但是看看你原来的编码字符串:空间在编码时变成了空间,但此时你已经“解码”了一个空间,然后才检查它是什么。你知道吗
你必须这样做:
但是,仍然存在一些细微的错误;更好的检查是验证每个字符是否可以在继续之前解码:
这样,你就可以对字母进行加密并传递其他信息。你知道吗
另外,考虑到凯撒密码的性质,
cipherDecrypt
的定义很简单:相关问题 更多 >
编程相关推荐