0

I'm trying to make a Text to Binary converter script. Here's what I've got..

userInput = input()
a = ('00000001')
b = ('00000010')
#...Here I have every remaining letter translated in binary.
z = ('00011010')

So let's say the user types the word "Tree", I want to convert every letter in binary and display it. I hope you can understand what I'm trying to do here. PS. I'm a bit newbie! :)

boaz_shuster
  • 2,825
  • 20
  • 26
Apost
  • 39
  • 1
  • 8
  • 1
    Possible duplicate of [Convert string to binary in python](https://stackoverflow.com/questions/18815820/convert-string-to-binary-in-python) – TheoretiCAL Aug 28 '17 at 23:31

3 Answers3

0

The way you have attempted to solve the problem isn't ideal. You've backed yourself into a corner by assigning the binary values to variables.

With variables, you are going to have to use eval() to dynamically get their value:

result = ' '.join((eval(character)) for character in myString)

Be advised however, the general consensus regarding the use of eval() and similar functions is don't. A much better solution would be to use a dictionary to map the binary values, instead of using variables:

characters = { "a" : '00000001', "b" :'00000010' } #etc

result = ' '.join(characters[character] for character in myString)

The ideal solution however, would be to use the built-in ord() function:

result = ' '.join(format(ord(character), 'b') for character in myString)
stelioslogothetis
  • 9,371
  • 3
  • 28
  • 53
0

Check the ord function:

userinput = input()
binaries = [ord(letter) for letter in userinput]
hd1
  • 33,938
  • 5
  • 80
  • 91
0

cheeky one-liner that prints each character on a new line with label

[print(val, "= ", format(ord(val), 'b')) for val in input()]
#this returns a list of "None" for each print statement

similarly cheeky one-liner to print with arbitrary seperator specified by print's sep value:

print(*[str(val) + "= "+str(format(ord(val), 'b')) for val in input()], sep = ' ')

Copy and paste into your favorite interpreter :)

Erich
  • 1,902
  • 1
  • 17
  • 23