How to convert a string to this encoding?

Asked

Viewed 303 times

0

I am trying to convert text into a binary language, but it keeps leaving letters in the result, I would like to create a text according to the numbering that each letter received:

a = 10000
c = 10011
d = 10000
e = 10000
f = 10000
g = 10000
h = 10000
i = 10000
j = 10000
l = 10000
m = 10000
n = 10000
o = 10000
p = 10000
q = 10000
r = 10000
s = 10000
t = 10000
u = 10000
v = 10000
w = 10000
x = 10000
y = 10000
z = 10000

texto = input('DIGITE UM TEXTO: ')

tam = len(texto)

for i in range(tam):
    print('{}' .format(texto[i]))

Can someone help me by pointing out the mistake?

  • The only letter of different value is c, it doesn’t seem to make sense. What should be the result?

2 answers

0

Instead of creating a variable for each letter of the alphabet, you should create a dictionary-like structure to convert the letters from one encoding to another. The iteration should also be modified. The code would look something like this:

alfabeto={'a':'1000','b':'1001','c':'1010'}

texto = input('DIGITE UM TEXTO: ')

saida=""

for letra in texto:
    saida=saida+alfabeto[letra]

print(saida)
  • Perfect, I didn’t remember this structure.

0


It’s quite simple actually, you can follow the example of our friend Daniel Reis. Follows the code:

letter = {
    'a':'',
    'b':'',
    'c':'',
    'd':'',
    'e':'',
    'f':'',
    'g':'',
    'h':'',
    'i':'',
    'j':'',
    'k':'',
    'l':'',
    'm':'',
    'n':'',
    'o':'',
    'p':'',
    'q':'',
    'r':'',
    't':'',
    'u':'',
    'v':'',
    'x':'',
    'w':'',
    'y':'',
    'z':'',
    'r':'',
}

phrase = input('Entre com uma frase:')
text = ''

for i in phrase:
    text += letter[i]

print(text)

Basically in the code you have a dictionary, a dictionary is nothing more than a variable that assigns a key to a given value, more used in lists that do not change their values and do not depend on an order to be consulted or displayed, basically like a dictionary itself.

In FOR, you will be going through each letter of the phrase that the user entered and including in the output variable by the value corresponding to the letter in the dictionary, which would be the key.

Hugs.

Browser other questions tagged

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