python 凯撒加密
时间: 2023-10-29 18:58:00 浏览: 50
凯撒加密是一种简单的替换加密方法,它通过将文本中的每个字母按照一定的偏移量进行替换来实现加密。在Python中,可以使用以下代码实现凯撒加密:
```python
def caesar_encrypt(text, shift):
encrypted_text = ""
for char in text:
if char.isalpha(): # 只对字母进行加密,忽略其他字符
ascii_offset = ord('a') if char.islower() else ord('A') # 确定字母的 ASCII 偏移量
encrypted_char = chr((ord(char) - ascii_offset + shift) % 26 + ascii_offset)
# 加密过程:将字符转换为 ASCII 码,减去偏移量,取模 26(字母个数),再加上偏移量,最后转换为字符
encrypted_text += encrypted_char
else:
encrypted_text += char # 非字母字符保持不变
return encrypted_text
```
使用示例:
```python
text = "Hello, World!"
shift = 3
encrypted_text = caesar_encrypt(text, shift)
print(encrypted_text) # 输出:Khoor, Zruog!
```
这段代码将给定文本中的每个字母向右偏移3个位置,得到加密后的文本。注意,该加密方法是基于英文字母,并且不区分大小写。解密过程与加密过程类似,只需将偏移量改为负数即可。