问:是时候练习我们的间谍技术,并对一个简单的密码进行编码了。编写一个函数encode(),该函数要求用户对要编码的消息和整数键值进行编码。密码将通过将密钥添加到字符的Unicode值来移动消息中的每个字符。例如,‘A’(unicode 65)移动3产生‘D’(unicode 68)。
请确保您的输出仅为密码文本。
产出应是:
输入一条信息:时间到了,海象说
输入一个键:7
[ol'{ptl'ohz'jvtl3'{ol'^hsyz'zhpk
发布于 2022-02-19 19:13:14
这是一个简单的凯撒密码,这是代码
def encrypt(text, s):
result = ""
# transverse the plain text
for i in range(len(text)):
char = text[i]
# Encrypt uppercase characters in plain text
if (char.isupper()):
result += chr((ord(char) + s-65) % 26 + 65)
# Encrypt lowercase characters in plain text
else:
result += chr((ord(char) + s - 97) % 26 + 97)
return result
发布于 2022-02-20 14:14:14
您可以使用chr()
和ord()
移动每个字符,并使用join()
将结果重新组合在一起:
s = "The time has come, the Walrus said"
k = 7
e = "".join(chr(ord(c)+k) for c in s)
print(e)
[ol'{ptl'ohz'jvtl3'{ol'^hsy|z'zhpk
https://stackoverflow.com/questions/71188245
复制相似问题