输入字符串,用凯撒密码加密
时间: 2023-05-22 15:01:00 浏览: 116
非常感谢您的提问!以下是用凯撒密码加密字符串的代码示例:
```python
def caesar_cipher(text, shift):
result = ""
for char in text:
if char.isalpha():
# 获取字符的 ASCII 码值
ascii_code = ord(char)
# 根据偏移量计算新的 ASCII 码值
new_ascii_code = (ascii_code - 65 + shift) % 26 + 65
# 将新的 ASCII 码值转换为字符
new_char = chr(new_ascii_code)
result += new_char
else:
result += char
return result
```
其中,`text` 参数表示要加密的字符串,`shift` 参数表示偏移量,可以是任意整数。该函数会返回加密后的字符串。
例如,如果要将字符串 "HELLO WORLD" 用凯撒密码加密,偏移量为 3,可以这样调用函数:
```python
encrypted_text = caesar_cipher("HELLO WORLD", 3)
print(encrypted_text) # 输出:KHOOR ZRUOG
```
希望这个代码示例能够帮助您!