利用ord()和chr()编写凯撒加密程序
时间: 2024-05-08 10:17:08 浏览: 9
加密:
```python
def caesar_encrypt(text, key):
result = ""
for char in text:
if char.isalpha(): # 判断是否为字母
if char.isupper(): # 判断大写字母
result += chr((ord(char) + key - 65) % 26 + 65)
else: # 小写字母
result += chr((ord(char) + key - 97) % 26 + 97)
else: # 非字母字符
result += char
return result
```
解密:
```python
def caesar_decrypt(cipher, key):
result = ""
for char in cipher:
if char.isalpha(): # 判断是否为字母
if char.isupper(): # 判断大写字母
result += chr((ord(char) - key - 65) % 26 + 65)
else: # 小写字母
result += chr((ord(char) - key - 97) % 26 + 97)
else: # 非字母字符
result += char
return result
```
测试:
```python
text = "Hello, world!"
key = 3
cipher = caesar_encrypt(text, key)
print(cipher) # Khoor, zruog!
plain = caesar_decrypt(cipher, key)
print(plain) # Hello, world!
```