加密:
str=input("请输入明文字符串:")
n=int(input("请输入偏移量:"))
str_encrypt=""
for i in str:
if i==" ":
i_encrypt=" "
else:
i_encrypt=chr((ord(i)-ord("a")+n)%26+ord("a"))
str_encrypt=str_encrypt+i_encrypt
print("输出加密过后的密文:",str_encrypt)
首先输入字符串和偏移量,这个是对小写字符的加密。当碰见空格时直接不加密直接输出空格即可。当是小写字母时直接先用ord()函数将字符串转换成数字加上偏移量后,再模上26 再加上a对应的数字即可。chr()函数是将数字转换成对应的字符串。
解密:
str_encrypt=input("请输入加密后的密文:")
n=int(input("请输入偏移量:"))
str_decrypt=""
for i in str_encrypt:
if i==" ":
word=" "
else:
word=chr((ord(i)-ord("A")-n)%26+ord("A"))
str_decrypt=str_decrypt+word
print("输入解码后的明文:",str_decrypt)
这是对大写的字符串进行解密,如果想对小写的英文进行解密,直接将上述大写的A转换成小写的a即可。
综上所述即可在一个脚本当中通过判断来进行加解密。
str=input("请输入加密的字符串:")
n=int(input("请输入偏移量:"))
str_encrypt=""
for i in str:
if i>="a" and i<="z":
word1=chr((ord(i)-ord("a")-n)%26+ord("a"))
str_encrypt=str_encrypt+word1
elif i>="A" and i<="Z":
word2=chr((ord(i)-ord("A")-n)%26+ord("A"))
str_encrypt=str_encrypt+word2
else:
str_encrypt=str_encrypt+i
print("输出加密后的密文:",str_encrypt)
如果要想进行加密和上述的原理一样直接把减n变成加n即可。(附上运行结果)