我以为我已经学会了足够的python来制作凯撒密码,所以我开始制作它并且我已经碰到了一堵砖墙。
这是我的代码:
phrase = raw_input("Enter text to Cipher: ")
shift = int(raw_input("Please enter shift: "))
result = ("Encrypted text is: ")
for character in phrase:
x = ord(character)
x = x + shift
print chr(x)
目前如果短语为'hi'且shift为1,则for循环只围绕字母i循环,而不是字母h,所以我的结果是:j
我想绕着整个单词循环,并按照变量int变量移动每个字母。
如何循环短语变量?
答案 0 :(得分:2)
您的代码正在打印ord()
'j'
的值,因为在循环结束时字符等于'i'
。您应该将新字符存储到列表中,并在循环结束后加入它们然后打印。
new_strs = []
for character in phrase:
x = ord(character)
x = x + shift
new_strs.append(chr(x)) #store the new shifted character to the list
#use this if you want z to shift to 'a'
#new_strs.append(chr(x if 97 <= x <= 122 else 96 + x % 122))
print "".join(new_strs) #print the new string
<强>演示:强>
$ python so.py
Enter text to Cipher: hi
Please enter shift: 1
ij
答案 1 :(得分:1)
将每个加密字符附加到result
字符串。
phrase = raw_input("Enter text to Cipher: ")
shift = int(raw_input("Please enter shift: "))
result = ""
for character in phrase:
x = ord(character)
result += chr(x + shift)
print result
答案 2 :(得分:0)
尝试:
phrase = raw_input("Enter text to Cipher: ")
shift = int(raw_input("Please enter shift: "))
result = ("Encrypted text is: ")
import sys
for character in phrase:
x = ord(character)
x = x + shift
sys.stdout.write(chr(x))
sys.stdout.flush()