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

2020-02-16 05:02发布

问题:

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