As well as the another answer says, you don’t need to turn your code into a list because strings are already indexed by position, acting as a list where each character will have its index.
texto = "Hello World"
print(texto[6]) # Podemos obter o caractere de um índice: ( W )
print(texto[2:10]) # Assim como podemos utilizar slice nela: ( llo Worl )
To continue getting user inputs, you can use the repeat structure while
which will repeat the entire code block.
One thing that got me confused is how to finish the execution of the code. In another answer, will be checked if the entry is "fim"
after decoding the message, but you didn’t make that very clear in the question.
If to finish the input should be "fim"
without being encoded in numbers, you cannot use the method split()
directly. You will need to check the input before any action or else the message will be separated and your code may even generate an error.
while True:
mensagem = input("Mensagem (Codificada): ")
if mensagem.lower() == "fim": break
As you can see, to stop the replay, simply use the command break
to leave the structure immediately.
To decode the message is quite simple, just split it as you did using the split
and then run it in a loop for
. Within the repeat structure, you must convert each input number to integer and thus get the character in your code string related to this number, as well as show the another answer.
If you want, you can create an even more simplified function that is using the method join
and comprehensilist on to carry out the whole process in a single line.
See the code below:
def decodificar(numeros):
codigo = " abcdefghijklmnopqrstuvwxyz"
return "".join([codigo[num] if 0 <= num < len(codigo) else "" for num in numeros])
while True:
mensagem = input("Mensagem (Codificada): ")
if mensagem.lower() == "fim": break
numeros = [int(num) for num in mensagem.split()]
palavra = decodificar(numeros)
print(palavra)
decoficidada ? kkk
– JeanExtreme002
@Jeanextreme002 Corrected :-)
– hkotsubo
Thank you very much for the explanations! :)
– user186294