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

Python 凯撒密码只打印最后一封信,python,Python,每当我运行它时,只有最后一个字母会被移位号移位。例如,如果我将“you”移动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',

每当我运行它时,只有最后一个字母会被移位号移位。例如,如果我将“you”移动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))

预先创建
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
试试这个:

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'

我认为您应该尝试以下解决方案:

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'

既然函数返回的是
shiftedChar
(可能是单个字符),为什么您会惊讶于它只打印单个字符?如果您想要一个完整的字符串,您应该返回一个完整的字符串。还可以像
shiftedChar=''
一样为循环定义
shiftedChar
。否则,对于一个只有空格的字符串,将生成错误还有您为什么要这样做-
列表(消息)
?可能是重复的,那么,使用您的建议将消息的移位数
“xyz”
移位300会给出什么结果?
alpha
仅包含52个元素,因此,您的解决方案将引发一个
索引器
!使用模运算也将有助于将列表
alpha
的大小减少到26。此外,检查
char
是否在
alpha
中也将有助于避免其他非字母字符。我并不是说我解决了创建ceaser密码的整个任务。问题的重点是只改变最后一个字母。