问题:你想用 Python 实现凯撒密码来加密和解密文本。
解决方案: 凯撒密码是一种简单的置换密码,它将字母表中的字符移动固定的位置。
下面是如何在 Python 中实现它:
def caesar_cipher(text, shift):
result = ""
for char in text:
if char.isalpha():
# Determine if the character is uppercase or lowercase
is_upper = char.isupper()
char = char.lower() # Convert to lowercase for shifting
shifted = chr(((ord(char) - ord('a') + shift) % 26) + ord('a'))
if is_upper:
shifted = shifted.upper() # Convert back to uppercase if necessary
result += shifted
else:
result += char # Non-alphabet characters remain unchanged
return result
# Example Usage:
text = "Hello, World!"
shift = 3
encrypted = caesar_cipher(text, shift)
decrypted = caesar_cipher(encrypted, -shift)
print("Original: ", text)
# Original: Hello, wiorld!
print("Encrypted: ", encrypted) # Encrypted: Khoor, Zruog!
print("Decrypted: ", decrypted) # Decrypted: Hello, World!
这段代码定义了一个 caesar_cipher 函数,该函数将文本和移位值作为输入,并返回加密后的文本。要解密,只需使用移位值的负数即可。示例演示了信息的加密和解密。