方法一: 将已知列表中的值赋值给字符变量
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.youkuaiyun.com/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.youkuaiyun.com/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.youkuaiyun.com/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='')