凯撒加密python代码
时间: 2023-10-15 12:11:24 浏览: 61
以下是凯撒加密的 Python 代码:
```python
def caesar_cipher(text, shift):
result = ""
# 遍历文本中的每个字符
for i in range(len(text)):
char = text[i]
# 加密大写字母
if char.isupper():
result += chr((ord(char) + shift - 65) % 26 + 65)
# 加密小写字母
elif char.islower():
result += chr((ord(char) + shift - 97) % 26 + 97)
# 忽略非字母字符
else:
result += char
return result
```
这个函数接受两个参数:要加密的文本和一个整数表示加密的位移量。它返回一个加密后的字符串。注意,这个函数只能加密字母,忽略其他字符。加密过程是将每个字母的 ASCII 码值加上位移量,然后通过模运算将结果限制在字母表范围内。
相关问题
凯撒加密Python代码实现
你好,以下是凯撒加密的 Python 代码实现:
```python
def caesar_cipher(text, shift):
result = ""
for char in text:
if char.isalpha():
if char.isupper():
result += chr((ord(char) + shift - 65) % 26 + 65)
else:
result += chr((ord(char) + shift - 97) % 26 + 97)
else:
result += char
return result
```
其中,text 是要加密的文本,shift 是加密的位移量。该函数会返回加密后的文本。
希望能对你有所帮助。
凯撒加密的python代码
以下是凯撒加密的Python代码,其中包括两种实现方式:
1. 加减法运算实现:
```python
# 加减法运算实现凯撒加密
def caesar_encrypt(text, key):
result = ""
# 遍历明文中的每个字符
for i in range(len(text)):
char = text[i]
# 如果是大写字母
if char.isupper():
result += chr((ord(char) + key - 65) % 26 + 65)
# 如果是小写字母
elif char.islower():
result += chr((ord(char) + key - 97) % 26 + 97)
# 如果是其他字符
else:
result += char
return result
```
2. 取模运算及零下索引实现:
```python
# 取模运算及零下索引实现凯撒加密
def caesar_encrypt_v2(text, key):
result = ""
# 遍历明文中的每个字符
for i in range(len(text)):
char = text[i]
# 如果是大写字母
if char.isupper():
result += chr((ord(char) - 65 + key) % 26 + 65)
# 如果是小写字母
elif char.islower():
result += chr((ord(char) - 97 + key) % 26 + 97)
# 如果是其他字符
else:
result += char
return result
```
使用示例:
```python
text = "hello world"
key = 3
encrypted_text = caesar_encrypt(text, key)
print("加减法运算实现加密结果:", encrypted_text) # 输出:khoor zruog
encrypted_text_v2 = caesar_encrypt_v2(text, key)
print("取模运算及零下索引实现加密结果:", encrypted_text_v2) # 输出:khoor zruog
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)