如何用python代码实现英文字符串凯撒加密
时间: 2024-03-10 17:50:55 浏览: 31
可以使用以下代码实现凯撒加密:
```python
def caesar_encrypt(text, shift):
result = ""
for char in text:
if char.isalpha():
# 获取字符的 ASCII 码值
ascii_code = ord(char)
# 通过移位得到新的 ASCII 码值
new_ascii_code = (ascii_code - ord('a') + shift) % 26 + ord('a')
# 将新的 ASCII 码值转换为字符并添加到结果字符串中
result += chr(new_ascii_code)
else:
# 非字母字符直接添加到结果字符串中
result += char
return result
```
这段代码定义了一个 `caesar_encrypt` 函数,它接收两个参数:待加密的字符串 `text` 和移位数 `shift`。函数中使用了一个 for 循环遍历字符串中的每个字符,对于字母字符,通过移位得到新的 ASCII 码值,然后将其转换为字符并添加到结果字符串中;对于非字母字符,直接添加到结果字符串中。最后返回加密后的字符串。
以下是一个示例:
```python
text = "hello world"
shift = 3
encrypted_text = caesar_encrypt(text, shift)
print(encrypted_text) # "khoor zruog"
```
这个例子中,待加密的字符串是 "hello world",移位数为 3,加密后的结果是 "khoor zruog"。