如何替换字符串中的特定字符(python)

如何替换字符串中的特定字符(python),python,Python,我想用Python制作一个凯撒密码。我快完成了,但是在转换像'' message = input('What is your message? ') shift = input('What number do you want to shift the letters in your message by? ') def Cipher(message,shift): final_cipher = '' for ch in message: shift_conver

我想用Python制作一个凯撒密码。我快完成了,但是在转换像
''

message = input('What is your message? ')
shift = input('What number do you want to shift the letters in your message by? ')
def Cipher(message,shift):
    final_cipher = ''
    for ch in message:
        shift_convert = ord(ch) + int(shift)
        print(shift_convert)

Cipher(message,shift)
当我使用消息
“test run”
运行此代码时,我得到以下信息:

118
103
117
118
34
116
119
112

我将如何更改
34
shift\u convert
中的
34
?我正在考虑减去移位值,将其转换回
'
,但我不知道如何实现这一点。你能给我一些提示吗?

如果我正确理解你的问题,你就不想改变空格/34,对吗? 您只需检查
ord(char)
是否为32

message=input('您的消息是什么?')
shift=input('您希望将邮件中的字母移位到哪个数字?')
def密码(消息、班次):
最终密码=“”
对于ch in消息:
移位转换=ord(ch)+如果ord(ch)!=32其他作战需求文件(ch)
打印(shift\u转换)
密码(信息、移位)

您可以将
if
else
语句添加到
shift\u convert
变量中:

shift_convert = ord(ch) + int(shift) if ch != ' ' else 32

试试这个,只需添加一个if语句来检查它是否是一个空格

message = input('What is your message? ')

shift = input('What number do you want to shift the letters in your message by? ')

def Cipher(message,shift):
    final_cipher = ''
    for ch in message:
        if(ord(ch) != 32):
            shift_convert = ord(ch) + int(shift)
            print(shift_convert)
        else:
            print(ord(ch))
Cipher(message,shift)

z的移位是什么?哦,我甚至没有想到,z的移位是{谢谢你提出了这个问题,明白了!-z移位1(到a)的解决方案需要对ord加上
shift
值进行模运算。
chr(97+(ord+shift-97)%26)
(其中ord_uu是字符的
ord
。当然,您不必对空格、标点符号、大写字母处理此语句,只需将它们与ord值一起传递。(
if 97