How can I make my Vigenère Cipher ignore spaces in the original message

早过忘川 提交于 2019-12-18 09:46:48

问题


Im trying to make a Vigenère Cipher but I can't seem to find a way to implement a feature that ignores in-putted white spaces when entering the message and then printing the final for example: I enter the starting message: "python computing" then I enter the key as: "stack" I expect to get if the program ignores spaces in the original message: "isukzg wppannjqr" but instead I get: "isukzgwppannjqr". Anyone know how I can solve this. I have considered using ords but I havent found a way to implement it. Code below:

def translateMessage(key, message, mode):
    translated = ""

    keyIndex = 0
    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

    return translated

if __name__ == '__main__':
    fetch_user_inputs()

回答1:


You just need to add an else statement in translateMessage() to add the space to the output like this

def translateMessage(key, message, mode):
    translated = ""

    keyIndex = 0
    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


来源:https://stackoverflow.com/questions/34800393/how-can-i-make-my-vigen%c3%a8re-cipher-ignore-spaces-in-the-original-message

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!