题解 | #字符串加解密#
字符串加解密
https://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a
m = input() # 要加密的字符
n = input() # 要解密的字符
# 加密函数
def encrypt(chars):
encrypted_chars = [] # 用来保存字符加密后的密文
for char in chars:
# 加密字母
if char.isalpha():
# 加密大写字母
if char.isupper():
if char == "Z":
encrypted_chars.append("a")
else:
encrypted_chars.append(chr(ord(char) + 1).lower())
# 加密小写字母
if char.islower():
if char == "z":
encrypted_chars.append("A")
else:
encrypted_chars.append(chr(ord(char) + 1).upper())
# 加密数字
elif char.isdigit():
if char == "9":
encrypted_chars.append("0")
else:
encrypted_chars.append(str(int(char) + 1))
# 其他字符
else:
encrypted_chars.append(char)
return encrypted_chars
# 解密函数
def decrypt(chars):
decrypted_chars = [] # 存储解密后的明文
for char in chars:
# 解密字母
if char.isalpha():
# 解密大写字母
if char.isupper():
if char == 'A':
decrypted_chars.append('z')
else:
decrypted_chars.append(chr(ord(char)-1).lower())
# 解密小写字母
elif char.islower():
if char == 'a':
decrypted_chars.append('Z')
else:
decrypted_chars.append(chr(ord(char)-1).upper())
# 解密数字
elif char.isdigit():
if char == '0':
decrypted_chars.append('9')
else:
decrypted_chars.append(str(int(char)-1))
# 其他字符
else:
decrypted_chars.append(char)
return decrypted_chars
print(''.join(encrypt(m)))
print(''.join(decrypt(n)))
查看5道真题和解析