用Python字典实现凯撒密码
时间: 2023-11-05 15:08:07 浏览: 61
凯撒密码是一种简单的加密方法,它将明文中的每个字母都按照一定的偏移量进行替换,从而得到密文。实现凯撒密码可以使用Python中的字典来存储明文和密文之间的一一对应关系。
以下是一个简单的凯撒密码实现示例:
```python
def caesar_cipher(message, shift):
# 定义明文和密文字典
plain = 'abcdefghijklmnopqrstuvwxyz'
cipher = ''
for i in range(len(plain)):
cipher += plain[(i + shift) % 26]
# 加密明文
encrypted_message = ''
for letter in message:
if letter in plain:
encrypted_message += cipher[plain.index(letter)]
else:
encrypted_message += letter
return encrypted_message
# 测试代码
message = 'hello world'
shift = 3
encrypted_message = caesar_cipher(message, shift)
print('加密后的密文:', encrypted_message)
```
在上述代码中,我们定义了一个明文字典 `plain`,其中存储了所有小写字母。然后,我们根据偏移量 `shift` 来生成相应的密文字典 `cipher`。接下来,我们遍历明文中的每个字母,如果它在明文字典中存在,则查找它在明文字典中的索引,并将对应的密文字典中的字符加入到加密后的密文中。最后,返回加密后的密文。
然后,我们将明文字符串 `'hello world'` 与偏移量 `3` 传入 `caesar_cipher` 函数中进行加密。运行程序后,输出结果为:
```
加密后的密文: khoor zruog
```
可以看到,原始的明文字符串 `'hello world'` 被成功加密成了 `'khoor zruog'`。