3.python请编写一个加密程序。实现输入一行字符串,将其每个字母加密后 输出。提示:凯撒密码。
时间: 2023-05-11 21:03:10 浏览: 83
以下是 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
text = input("请输入要加密的字符串:")
shift = int(input("请输入加密偏移量:"))
print("加密后的字符串为:", caesar_cipher(text, shift))
```
输入要加密的字符串和加密偏移量后,程序会输出加密后的字符串。
例如,输入字符串 "hello world" 和偏移量 3,程序会输出加密后的字符串 "khoor zruog"。
注意:凯撒密码是一种简单的加密方式,容易被破解,不适合用于真正的加密场景。
相关问题
简单的python凯撒加密编写程序、要求输入一个字符串_新手求助:在Python里面编一个类似凯撒密码的程序,急啊!!!...
好的,下面是一个简单的凯撒密码加密代码,可以用来加密输入的字符串:
```python
class CaesarCipher:
def __init__(self, shift):
self.shift = shift
def encrypt(self, message):
cipher_text = ""
for char in message:
if char.isupper():
cipher_text += chr((ord(char) + self.shift - 65) % 26 + 65)
elif char.islower():
cipher_text += chr((ord(char) + self.shift - 97) % 26 + 97)
else:
cipher_text += char
return cipher_text
```
这个类接受一个整数 `shift` 作为参数。`encrypt` 方法将输入的字符串转换为凯撒密码并返回加密后的字符串。
使用方法如下:
```python
cipher = CaesarCipher(3)
message = input("请输入要加密的字符串:")
encrypted_message = cipher.encrypt(message)
print("加密后的字符串:", encrypted_message)
```
在上面的示例中,我们创建了一个 `CaesarCipher` 对象,并将其初始化为一个偏移量为 3 的凯撒密码。然后,我们从用户那里获取输入的字符串,并将其加密。最后,我们将加密后的字符串打印出来。
编写一个程序实现凯撒加密:输入一个字符串,对字符串中的字母和数字进行加密(规定加密偏移量为3,即后移三位),并输出加密后的字符串。
好的,以下是实现凯撒加密的 Python 代码:
```python
def caesar_cipher(text):
result = ""
for char in text:
if char.isalpha():
if char.isupper():
result += chr((ord(char) + 3 - 65) % 26 + 65)
else:
result += chr((ord(char) + 3 - 97) % 26 + 97)
elif char.isdigit():
result += str((int(char) + 3) % 10)
else:
result += char
return result
```
你可以将要加密的字符串作为参数传递给这个函数,它将返回加密后的字符串。