3

我以为我已经学会了足够多的蟒蛇来制作凯撒密码,所以我开始制作它,但我已经碰壁了。

这是我的代码:

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

我想循环整个单词并通过 shift int 变量来移动每个字母。

如何循环短语变量?

4

3 回答 3

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
于 2013-08-03T07:16:42.553 回答
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
于 2013-08-03T07:16:31.573 回答
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()
于 2013-08-03T07:39:18.787 回答