Doubt strings Pyhton

Asked

Viewed 115 times

7

I created an algorithm that encrypts words and messages. To work it needs a simple numeric key, such as 9, 4, 2, where the first letter will be displaced 9 positions, the second 4, etc.

All running perfectly with the code below

import string

alfabeto = string.ascii_uppercase  
msg = 'sendmoremoney'
msg = msg.upper() 
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) + int(chave[posicao])) % 26 
    resultado += alfabeto[mod_a]
    posicao += 1
print(resultado)
pausa = input('\n')

However, if I comment on the line msg = msg.upper() the sequence obtained with the answer is another quite different.

I did not understand why the answer was modified by deleting that line since the answer should be based on the values within the variable alfabeto

1 answer

8


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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.