【python】恺撒密码的五种方法

方法一: 将已知列表中的值赋值给字符变量

A = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
a = input()
for i in a:
    if i in A:
        b = A[(ord(i) - ord('A') + 3) % 26]
    elif i.upper() in A:
        b = A[(ord(i) - ord('a') + 3) % 26].lower()
    else:
        b = i
    print(b,end='')

方法二: 先求出包含所输入内容的密文的列表,最后将其转换成字符串

摘自:https://blog.csdn.net/u013378642/article/details/80874581
(侵删哈~)

def encryption(str, n):
    cipher = []
    for i in range(len(str)):
        if str[i].islower():
            if ord(str[i]) < 123-n:
                c = chr(ord(str[i]) + n)
                cipher.append(c)
            else:
                c = chr(ord(str[i]) + n - 26)
                cipher.append(c)
        elif str[i].isupper():
            if ord(str[i]) < 91-n:
                c = chr(ord(str[i]) + n)
                cipher.append(c)
            else:
                c = chr(ord(str[i]) + n - 26)
                cipher.append(c)
        else:
            c = str[i]
            cipher.append(c)
    cipherstr = ('').join(cipher)
    return cipherstr

#获得用户输入的明文
plaintext = input()
ciphertext = encryption(plaintext, 3)
print(ciphertext)

方法三: 方法二的简化

def encryption(str, n):
    cipher = []
    for i in range(len(str)):
        if str[i].islower(): #该字母为小写字母
            c = chr(ord('a') + (ord(str[i]) - ord('a') + n) % 26)
            cipher.append(c)
        elif str[i].isupper():
            c = chr(ord('A') + (ord(str[i]) - ord('A') + n) % 26)
            cipher.append(c)
        else:
            c = str[i]
            cipher.append(c)
    cipherstr = ('').join(cipher)
    return cipherstr

#获得用户输入的明文
plaintext = input()
ciphertext = encryption(plaintext, 3)
print(ciphertext)

方法四: 边求密文字符的unicode编码,边进行字符串连接

以下方法引用自:https://blog.csdn.net/StefanCharlie/article/details/83148498
据说是标答(侵删)

s = input()
t = ""
for c in s:
    if 'a' <= c <= 'z': #str是可以直接比较的
        t += chr( ord('a') + ((ord(c)-ord('a')) + 3 )%26 )
    elif 'A'<=c<='Z':
        t += chr( ord('A') + ((ord(c)-ord('A')) + 3 )%26 )
    else:
        t += c
print(t)

方法五:先求出所有密文字符的unicode编码,最后进行字符串的转换

以下方法引用自:https://blog.csdn.net/StefanCharlie/article/details/83148498
(侵删)

a = input()
for i in range(len(a)):
    if ord('a') < ord(a[i]) < ord('z'):
        b = ord('a') + (ord(a[i]) - ord('a') + 3) % 26
    elif ord('A') < ord(a[i]) < ord('Z'):
        b = ord('A') + (ord(a[i]) - ord('A') + 3) % 26
    else:
        b = ord(a[i])
    r = chr(b)
    print(r,end='')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值