你好,我对编码非常陌生,正在研究凯撒密码。但是对于这段代码`def encoder():user_string=str(input('Enter text to encrypt'))shift=int(input('Enter number to shift letters by'))for i in range(len(user_string)): char=user_string[i] value=ord(char) new_value=value+shift new_value=chr(new_value) print(new_value,end='')def decoder():user_string=str(input('Enter text to decrypt'))shift=int(input('Enter number to shift letters by'))for i in range(len(user_string)): char=user_string[i] value=ord(char) new_value=value-shift new_value=chr(new_value) print(new_value,end='')当我插入像 Hello world 这样的东西时,它会返回正确的结果,但用 # 替换空格。当我将加密结果插入解码器时,它返回完全没有空格的字符串。两者之间的唯一区别应该是使用 newvalue = value + shift 进行编码,然后使用 newvalue = value-shift 进行解密。有人可以帮助我理解为什么要这样做以及如何解决加密中的 # 和解密中没有空格的问题。谢谢。编辑我使用的移位值是 3,确切的字符串是用于加密的 Hello world 和用于解密的相同字符串的编码版本。
1 回答
繁星淼淼
TA贡献1775条经验 获得超11个赞
这是因为空间也移动了 3。你的程序是绝对正确的。
空格的 ASCII 代码是 32,# 的 ASCII 代码是 35。
encoder()
with Hello world
& 3
shift 应该结果Khoor#zruogv
decoder()
with Khoor#zruogv
& 3
shift 应该结果Hello world
如果您希望空格不移动并显示为空格,可以在 for 循环内放置 if 语句。
for i in range(len(user_string)):
char=user_string[i]
if char == ' ':
print(char, end='')
continue
value=ord(char)
new_value=value+shift
new_value=chr(new_value)
print(new_value,end='')
添加回答
举报
0/150
提交
取消