凯撒密码Python-附加功能 [英] Caesar Cipher Python - Additional Features
问题描述
所以目前,我的代码看起来像这样(感谢我撰写的另一篇文章)
So currently, my code looks like this (thanks to help in another post I made)
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
The problem is, if I type in more than one word for example: hello world , with a shift of 1
输出为:ifmmp!xpsme
感叹号出现一个空格(根据移位而变化).我当时正在考虑做一个if语句来检测空格:
The exclamation mark shows up for a space (varies depending on shift). I was thinking of doing an if statement to detect spaces:
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"
但是我不知道如何在结果变量中添加空格.另外,我在此线程中看到:使用python的凯撒密码,可以用一点帮助
But I don't know how to add the space into the result variable. Also, I saw in this thread: Caesar's Cipher using python, could use a little help
JeffB使用while循环处理ASCII表32为空格而127为DEL.他为什么使用96?我不明白.
That JeffB used a while loop for dealing with the ASCII table 32 being space and 127 being DEL. Why did he use 96? I don't understand.
while x < 32:
x += 96
while x > 127:
x -= 96
抱歉,这个问题很长.提前谢谢了!您的帮助对我来说是无价之宝.
Sorry this question is rather long. Many thanks in advance! Your help is invaluable to me.
推荐答案
您可以跳过空格:
for character in phrase:
x = ord(character)
if character == ' ':
result += ' '
else:
result += chr(x + shift)
您的班次不会将输出限制为仅ASCII.如果要确保这一点,则应使用模运算符:
Your shift won't restrict the output to just ASCII. If you want to ensure that, you should use the modulo operator:
chr(32 + (x + shift) % (127 - 32))
这篇关于凯撒密码Python-附加功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!