凯撒密码python
时间: 2023-07-25 09:15:07 浏览: 99
你好,关于凯撒密码的 Python 实现,可以参考以下代码:
```python
def caesar_cipher(text, shift):
"""
凯撒密码加密函数
:param text: 待加密的字符串
:param shift: 加密偏移量
:return: 加密后的字符串
"""
cipher_text = ""
for char in text:
if char.isalpha():
# 将字母转换为 ASCII 码,加上偏移量
# ord() 函数可以将字符转换为 ASCII 码
# chr() 函数可以将 ASCII 码转换为字符
cipher_char = chr((ord(char.upper()) - 65 + shift) % 26 + 65)
else:
cipher_char = char
cipher_text += cipher_char
return cipher_text
def caesar_decipher(cipher_text, shift):
"""
凯撒密码解密函数
:param cipher_text: 待解密的字符串
:param shift: 解密偏移量
:return: 解密后的字符串
"""
text = ""
for char in cipher_text:
if char.isalpha():
# 将字母转换为 ASCII 码,减去偏移量
text_char = chr((ord(char.upper()) - 65 - shift) % 26 + 65)
else:
text_char = char
text += text_char
return text
```
使用示例:
```python
# 加密
text = "hello world"
shift = 3
cipher_text = caesar_cipher(text, shift)
print(cipher_text)
# 解密
decipher_text = caesar_decipher(cipher_text, shift)
print(decipher_text)
```
输出:
```
KHOOR ZRUOG
hello world
```
希望能帮到你!
阅读全文