Python中的Caesar Cipher编码器

时间:2015-01-30 21:11:19

标签: python string python-3.x encryption

我正在尝试使用python编写一个简单的程序,使用Caesar密码对具有特定班次的字符串进行编码,但我的代码似乎无法正常工作。

这是我的代码:

n = int(input())
s = list(input())
for i in range(len(s)):
    if s[i] == " ":
        new = 32
    else:
        if s[i].isupper():
            new = ord(s[i]) + n
            while new > 122:
                new -= 26
        else:
            new = ord(s[i]) + n
            while new > 90:
                new -= 24
    s[i] = chr(new)
print ("".join(s))

你觉得这里有什么问题?

测试用例是:

12

Qx Bek Oazsdaa

这应该返回:

El Psy Congroo

1 个答案:

答案 0 :(得分:0)

你的122和90位置错误,24位应该是26位。

n = int(input())
s = list(input())
for i in range(len(s)):
    if s[i] == " ":
        new = 32
    else:
        if s[i].isupper():
            new = ord(s[i]) + n
            while new > 90:
                new -= 26
        else:
            new = ord(s[i]) + n
            while new > 122:
                new -= 26
    s[i] = chr(new)
print ("".join(s))

结果:

2
Hello abc XYZ
Jgnnq cde ZAB