There are some details you should be aware of:
- The original alphabet you are using is that of the module
string
, in case the string.ascii_uppercase
. What gives you the letters of the alphabet in uppercase (ABCDEF...)
- You are using the method
.find
string to find the position in the alphabet.
It turns out that as you are using an alphabet in uppercase letters, when you look for the position of a lowercase letter, the find
return to you -1
, this because he did not find, for example, the letter to in the alphabet ABCD....
How to get around this?
Instead of capitalizing the entire sentence, convert only the character when using. So you can still keep the phrase in the original format. I only modified 3 lines, to stay as follows:
import string
alfabeto = string.ascii_uppercase
msg = 'sEnDmOrEmOnEy'
#msg = msg.upper() ==> Não mais necessário
chave = [9, 0, 1, 7, 23, 15, 21, 14, 11, 11, 2, 8, 9]
resultado = ""
posicao = 0
for letra_m in msg:
mod_a = (alfabeto.find(letra_m.upper()) + int(chave[posicao])) % 26
resultado += alfabeto[mod_a] if letra_m.isupper() else alfabeto[mod_a].lower()
posicao += 1
print(resultado)
pausa = input('\n')
Note that I commented on the msg.upper()
, but then converted the character separately on the line:
mod_a = (alfabeto.find(letra_m.upper()) + int(chave[posicao])) % 26
So I can do what I did on the next line:
resultado += alfabeto[mod_a] if letra_m.isupper() else alfabeto[mod_a].lower()
Where I checked if before the character was uppercase or lowercase and then kept his condition. Explaining: as I know that in the alphabet I will find uppercase letters only I put one if letra_m.usupper()
to see if he was already mauled, so I won’t have losses. And in else
I just made the result tiny if the character was like this.