繁体   English   中英

Python-尝试编写不忽略空格的vigenere密码

[英]Python - Tried to write a vigenere cipher that doesn't ignore spaces

我试图更改我的Vigenere程序,以便它将输出带空格的消息。 它应该执行以下操作:translationMessage('JPZFR DTZA NKC HFHOUC','cloudy','d')=>'HELLO FROM the FUTURE'

 def translateMessage(message, key, mode):
    translated = ''
    alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    keyIndex = 0
    message = message.upper()
    key = key.upper()

    for symbol in message:
        xyz = alphabet.find(symbol.upper())
        if xyz != -1:
            if mode == 'encrypt' or 'e':
                xyz += alphabet.find(key[keyIndex]) + 1
            elif mode == 'decrypt' or 'd':
                xyz -= alphabet.find(key[keyIndex]) + 1

            xyz %= len(alphabet)

            if symbol.isupper():
                translated += alphabet[xyz]
            elif symbol.islower():
                translated += alphabet[xyz].lower()

            keyIndex += 1
            if keyIndex == len(key):
                keyIndex = 0
        else : translated += symbol #this will add space as it is

    return translated

相反,它给出以下内容:translationMessage('JPZFR DTZA NKC HFHOUC','cloudy','d')=>'MBOAV CWLP IOB KRWJYB'

您的代码看起来基本上没问题,但是您会注意到,无论选择哪种模式,都始终加密。

这是由您造成的

if mode == 'encrypt' or 'e':

线。 因为or具有比==更低的运算符优先级 ,所以它解析为:

if (mode == 'encrypt') or 'e':

由于mode为'd', (mode == 'encrypt')False 但是,由于'e'是一个非空字符串,因此在布尔上下文中其值为True 因此,无论您选择哪种模式, (mode == 'encrypt') or 'e'始终为True

您需要的是:

  if mode == 'encrypt' or mode =='e':

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM