我在加密或解密邮件时尝试保持标点符号不变
# 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))
功能。
有什么方法可以将实际标点符号添加到加密邮件中,而无需过多更改代码?非常感谢您的帮助!
答案 0 :(得分:0)
只需使用isalpha()
处理第一个条件中的所有非字母字符,只需更改一个线性即可获得所需的结果
# 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 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 z
print ("Your original message:",message)
print ("Your encrypted message:",encrypt)
print ("\t")
答案 1 :(得分:0)
与使用空格相同,您可以使用任何字符。
if char in string.punctuation+' ':
encrypt = encrypt + char