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))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值