Vigenere Cipher project

I was writing a function to code a message using the Vigenere Cipher. The message contained a capital at the beginning of the sentence. For some reason, when i printed the function, the translated message replaced the capital T with a lowercase z. Why would the decoded message change replace T with z?

def vigenere_coder(message, keyword):
    letter_pointer = 0
    keyword_final = ''
    for i in range(0,len(message)):
        if message[i] in punctuation: 
            keyword_final += message[i]
        else: 
            keyword_final += keyword[letter_pointer]
            letter_pointer = (letter_pointer+1)%len(keyword)
    translated_message = ''
    for i in range(0,len(message)):
        if message[i] not in punctuation:
            ln = alphabet.find(message[i]) + alphabet.find(keyword_final[i])
            translated_message += alphabet[ln % 26]
        else:
            translated_message += message[i]
    return translated_message

message_for_v = "Thank you for equipping me with the knowledge and skillset of tackling basic cipher messages."
keyword = "Besties"

print(vigenere_coder(message_for_v,keyword))
print(vigenere_decoder(vigenere_coder(message_for_v, keyword), keyword))

Here is the pre-written solution provided:

def vigenere_coder(message, keyword):
    letter_pointer = 0
    keyword_final = ''
    for i in range(0,len(message)):
        if message[i] in punctuation:
            keyword_final += message[i]
        else:
            keyword_final += keyword[letter_pointer]
            letter_pointer = (letter_pointer+1)%len(keyword)
    translated_message = ''
    for i in range(0,len(message)):
        if message[i] not in punctuation:
            ln = alphabet.find(message[i]) + alphabet.find(keyword_final[i])
            translated_message += alphabet[ln % 26]
        else:
            translated_message += message[i]
    return translated_message

message_for_v = "thanks for teaching me all these cool ciphers! you really are the best!"
keyword = "besties"

print(vigenere_coder(message_for_v,keyword))
print(vigenere_decoder(vigenere_coder(message_for_v, keyword), keyword))

It might depend a little on what you shifted it by but a capital letter has a different unicode value to a lowercase letter. If you used a modulo operation to get a value between 0 and 25 which you then used to look-up the replacement character then it could wind up with something unexpected. I note .find is in your solution which would return a -1 when it cannot locate the given substring within a string. Consider how that may be interpreted with modulo.

Either you’d have to take into account capital letters in your indexing or you could force all letters to the lower case and make the first letter in the new string a capital letter or something similar if this bothered you enough.

that makes sense. It’s not a big enough deal for me to go in and implement a change. I was just curious.

Thank you for the fast reply

1 Like