gpt4 book ai didi

python - Caesar Cipher Python - 附加功能

转载 作者:太空宇宙 更新时间:2023-11-04 10:45:01 36 4
gpt4 key购买 nike

所以目前,我的代码看起来像这样(感谢我在另一篇文章中的帮助)

phrase = raw_input("Enter text to Cipher: ")
shift = int(raw_input("Please enter shift: "))
result = ("Encrypted text is: ")

for character in phrase:
#Loops through phrase and shows ascii numbers, example: hello is: 104,101,108,108,111
x = ord(character)

#adds a shift to each character so if shift is 1 'hello' becomes: ifmmp 105,102,109,109,112
result += chr(x + shift)


print "\n",result,"\n"

问题是,如果我输入多个单词,例如:hello world,移位 1

输出是:ifmmp!xpsme

感叹号显示为空格(因类次而异)。我正在考虑做一个 if 语句来检测空格:

phrase = raw_input("Enter text to Cipher: ")
shift = int(raw_input("Please enter shift: "))
result = ("Encrypted text is: ")

for character in phrase:
#Loops through phrase and shows ascii numbers, example: hello is: 104,101,108,108,111
x = ord(character)

if x == ord(' '):
print "\nfound a space space"

#adds 1 to each character so 'hello' becomes: ifmmp 105,102,109,109,112
result += chr(x + shift)


print "\n",result,"\n"

但我不知道如何将空格添加到结果变量中。另外,我在这个线程中看到:Caesar's Cipher using python, could use a little help

JeffB 使用 while 循环来处理 ASCII 表 32 是空格,127 是 DEL。他为什么用96?我不明白。

while x < 32:
x += 96

while x > 127:
x -= 96

抱歉,这个问题太长了。提前谢谢了!您的帮助对我来说非常宝贵。

最佳答案

你可以直接跳过空格:

for character in phrase:
x = ord(character)

if character == ' ':
result += ' '
else:
result += chr(x + shift)

您的类次不会将输出限制为仅 ASCII。如果你想确保这一点,你应该使用模运算符:

chr(32 + (x + shift) % (127 - 32))

关于python - Caesar Cipher Python - 附加功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18031520/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com