python凯撒密码流程图_凯撒密码Python-附加功能

1586010002-jmsa.png

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"

The problem is, if I type in more than one word for example: hello world , with a shift of 1

the output is: ifmmp!xpsme

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"

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

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.

解决方案

You can just skip the space:

for character in phrase:

x = ord(character)

if character == ' ':

result += ' '

else:

result += chr(x + shift)

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凯撒密码流程图)