如何在凯撒密码中保持标点符号不变?- Python

我在加密或解密消息时试图保持标点符号不变


# encryption

message = input("Enter a message to be encrypted: ") # user inputs message to be encrypted

offset = int(input ("Enter an offset: ")) # user inputs offset

print ("\t")


encrypt = " " 


for char in message:

    if char == " ":

        encrypt = encrypt + char

    elif char.isupper():

        encrypt = encrypt + chr((ord(char) + offset - 65) % 26 + 65) # for uppercase Z

    else:

        encrypt = encrypt + chr((ord(char) + offset - 97) % 26 + 97) # for lowercase z


print ("Your original message:",message)

print ("Your encrypted message:",encrypt)

print ("\t")

如果我尝试使用标点符号(偏移量为 8)加密消息,则输出的示例如下:


Your original message: Mr. and Mrs. Dursley, of number four Privet Drive, were proud to say that they were perfectly normal, thank you very much.

Your encrypted message:  Uzj ivl Uzaj Lczatmgh wn vcujmz nwcz Xzqdmb Lzqdmh emzm xzwcl bw aig bpib bpmg emzm xmznmkbtg vwzuith bpivs gwc dmzg uckp

我怀疑由于chr(ord(char))功能的原因,该程序正在将标点符号更改为字母 。


有什么方法可以在不过多更改代码的情况下将实际标点添加到加密消息中?我真的很感激任何帮助,谢谢!


POPMUISE
浏览 266回答 2
2回答

慕莱坞森

通过使用处理第一个条件中的所有非字母字符,您只需更改一个班轮即可获得所需的结果 isalpha()# encryptionmessage = input("Enter a message to be encrypted: ") # user inputs message to be encryptedoffset = int(input ("Enter an offset: ")) # user inputs offsetprint ("\t")encrypt = " " for char in message:    if not char.isalpha(): #changed        encrypt = encrypt + char    elif char.isupper():        encrypt = encrypt + chr((ord(char) + offset - 65) % 26 + 65) # for uppercase Z    else:        encrypt = encrypt + chr((ord(char) + offset - 97) % 26 + 97) # for lowercase zprint ("Your original message:",message)print ("Your encrypted message:",encrypt)print ("\t")

繁星点点滴滴

就像你用空格做的一样,你可以用任何字符来做。if char in string.punctuation+' ':         encrypt = encrypt + char
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python