凯撒密码只打印最后一封信

时间:2017-05-01 12:43:44

标签: python

每当我运行它时,只有最后一个字母被移位号移动。例如,如果我将“你”移动3个字母,则只打印“x”而不是“brx” 我该如何解决这个问题?

alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
         'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f',
         'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
         'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']


def caesarShift(message):
    for char in message:
        if char == ' ':
            pass
        else:
            ind = alpha.index(char)
            newind = int(ind) + int(shift)
            shiftedChar = alpha[newind]
    return shiftedChar


message = input('Enter message here: ')
shift = input('Enter shift number: ')
print(caesarShift(message))

3 个答案:

答案 0 :(得分:0)

预先创建shifterChar,然后像这样添加字母:

def caesarShift(message):
    list(message)
    shiftedChar = ''
    for char in message:
        if char == ' ':
            pass
        else:
            ind = alpha.index(char)
            newind = int(ind) + int(shift)
            shiftedChar += alpha[newind]
    return shiftedChar

答案 1 :(得分:0)

试试这个:

def shiftCeasar(message, shift):
    # just an easy way to get from a to z...
    a_z = map(chr, range(ord('a'), ord('z')+1))

    _ = lambda x: a_z[(shift + a_z.index(x))%26]
    return ''.join([_(x) if x != ' ' else x for x in message])

使用它:

In [11]: shiftCeasar('this is a message', 0)
Out[11]: 'this is a message'
In [12]: shiftCeasar('this is a message', 11)
Out[12]: 'estd td l xpddlrp'
In [13]: shiftCeasar('this is a message', 2600)
Out[13]: 'this is a message'

答案 2 :(得分:0)

我认为你应该尝试这个解决方案:

alpha = [chr(i) for i in range(ord('a'), ord('z')+1)]

def caesarShift(message, shift):
    return ''.join([char if not char.isalpha() 
                    else alpha[(alpha.index(char)+shift)%26] 
                    for char in message])

给出了:

In [1]: caesarShift('you', 3)
Out[1]: 'brx'