请编写一个程序,对输入字符串进行恺撒密码加密,直接输出结果,其中空格不用进行加密处理。使用input()获得输入
时间: 2024-05-02 21:21:22 浏览: 8
原始字符串:hello world
加密后的字符串:khoor zruog
代码如下:
```python
s = input("请输入原始字符串:")
shift = 3 # 移位数为3
result = ""
for char in s:
if char == " ": # 空格不进行加密
result += " "
elif char.islower(): # 小写字母加密
result += chr((ord(char) - 97 + shift) % 26 + 97)
elif char.isupper(): # 大写字母加密
result += chr((ord(char) - 65 + shift) % 26 + 65)
else: # 非字母不加密
result += char
print("加密后的字符串:", result)
```
相关问题
请编写一个程序,对输入字符串进行恺撒密码加密或者解密,直接输出结果,其中空格不用进行加密或者处理。使用input()获得输入。 如输入: abcXYz 加密请输入1,解密请输入2:1输出:def ABC
YZ
代码如下:
```python
input_str = input("请输入需要加密或解密的字符串:")
mode = int(input("加密请输入1,解密请输入2:"))
if mode == 1:
shift = int(input("请输入加密的偏移量:"))
else:
shift = int(input("请输入解密的偏移量:")) * -1
result = []
for char in input_str:
if char == " ":
result.append(" ")
elif char.isupper():
result.append(chr((ord(char) - 65 + shift) % 26 + 65))
elif char.islower():
result.append(chr((ord(char) - 97 + shift) % 26 + 97))
else:
result.append(char)
print("".join(result))
```
假设用户可能使用的输入包含大小写字母a~zA~Z、空格和特殊符号,请编写一个程序,对输入字符串进行恺撒密码加密或者解密,直接输出结果,其中空格不用进行加密或者处理。使用input()获得输入。
好的,我可以帮你编写这个程序。以下是Python代码实现恺撒密码的加密和解密功能:
```python
def caesar_cipher(text, shift, action):
# 定义字母表
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
# 初始化加密/解密结果字符串
result = ''
# 处理每个字符
for char in text:
# 如果是空格则直接加入结果
if char == ' ':
result += ' '
# 如果是字母则进行加密/解密
elif char in alphabet:
# 获取字母在字母表中的位置
index = alphabet.index(char)
# 根据加密/解密操作进行位移
if action == 'encrypt':
new_index = (index + shift) % 52
elif action == 'decrypt':
new_index = (index - shift) % 52
# 将新位置对应的字母加入结果
new_char = alphabet[new_index]
result += new_char
# 如果是其他符号则直接加入结果
else:
result += char
return result
# 获取用户输入
text = input('请输入要加密/解密的字符串:')
shift = int(input('请输入位移数:'))
action = input('请输入操作(encrypt加密/decrypt解密):')
# 调用恺撒密码函数并输出结果
result = caesar_cipher(text, shift, action)
print(result)
```
这个程序会要求用户输入要加密/解密的字符串、位移数以及操作类型(加密/解密)。然后程序会根据用户输入的信息进行恺撒密码的加密/解密操作,并输出结果。