Python实现凯撒密码(加解密)
程序员文章站
2022-07-09 13:47:57
...
对输入字符进行编码
思路:利用字符对应的ASCII 码,进行移位,实现加解码
# 编码
def encode(x):
for i in x:
if i.isspace():
print(' ', end='')
continue
new_c = ord(i) - 29
if new_c > 90:
new_c -= 26
print(f'{chr(new_c)}', end='')
解码
# 解码
def decode(x):
for i in x:
if i.isspace():
print(' ', end='')
continue
new_c = ord(i) + 29
if new_c < 97:
new_c += 26
print(f'{chr(new_c)}', end='')
主程序入口
c = input('输入明文:')
if c.islower():
print('加密后为: ', end='')
encode(c)
elif c.isupper():
print('解密后为:',end='')
decode(c)
else:
print('输入错误!')
实现效果
D:\腾讯手游助手\python\python.exe D:/project/cryptography/Crypt.py
输入明文:omnia gallia est divasa in partes tres
加密后为: RPQLD JDOOLD HVW GLYDVD LQ SDUWHV WUHV
Process finished with exit code 0
输入明文:RPQLD JDOOLD HVW GLYDVD LQ SDUWHV WUHV
解密后为:omnia gallia est divasa in partes tres
Process finished with exit code 0