问题
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