Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text to Binary in Python

Tags:

python

I'm trying to write a binary translator - with a string as an input and its binary representation as output.

And I'm having some difficulties, I wrote in variable the translation for each letter, but they are variables, not strings, so I want to take an input from that matches with the name of the variable and prints the result:

a = "01000001"
b = "01000010"
c = "01000011"
d = "01000100"
# all the way to z


word = input("enter here: ")
print (word)

When I run this I enter a word and it just returns the same word to me but when I write print(a) it returns 01000010 but I can't get it to work with the input.

Can someone tell me where I'm doing something wrong?

like image 760
Eren Biçer Avatar asked May 29 '17 19:05

Eren Biçer


1 Answers

Following the comments of the users, is a better practice of programming using a dictionary for these cases, you just only have to fill in the dictionary letterToBin as you can see in the example

This is a dictionary, wich means it will have a key, and a value, like a cell phone, you have the key as a name (your mother) and the value (his cellphone):

letterToBin = {}

letterToBin = {
  "a" : "01000001", #Here, the key is the "a" letter, and the value, his bin transformation, the 01000001
  "b" : "01000010",
  "c" : "01000011",
  "d" : "01000100"
  #so you need to add all the other keys you need, for example the "e"
  "e" : "01000101" #for example
}




binToLetter = {} # here I create a second dictionary, and it invert the values of the first, it meas, now the keys will be the bins, and the value the latters
binToLetter = dict(zip(letterToBin.values(), letterToBin.keys())) #this code do the magic, you must understand, that only needs to feel the first dictionary, and for free, you will have the second dictionary

wordOrBin = input("enter here: ")

if wordOrBin in letterToBin:
  print(letterToBin[wordOrBin]) #here I has if you write a latter (a) or a bin(11001101) and it choose where to look the correct value
else:
  print(binToLetter[wordOrBin])
like image 186
A Monad is a Monoid Avatar answered Oct 04 '22 04:10

A Monad is a Monoid