0

I want to convert some input ASCII characters into bytes. Such as from 'a' to 01100001.
I have read answers like this. But sometimes it gives out 0b10000110 like 9 digits values. I am not sure if that's an error or that's the way it supposes to work. I have made something like this:

text = list(input("text: "))

for character in text:
    if character == ' ':
        byt = '00000000'
    else:
        byt = bin(ord(character))
    byt = byt.replace('b', '') #delete the 'b' in the output
    if len(byt) != 8:
        byt = '0' + byt
    print(byt)

It worked pretty well with normal characters. But when I entered weird characters like: 'B
It outputs very strangely:

001110
00100111
0010000000
01000010

I am not very experienced with Python, so I don't know if there is a way that you can write a function or other methods to do this.
I am using Python 3.6
Many thanks

Mike
  • 31
  • 1
  • 5

1 Answers1

3

The insight you are looking for is:

>>> '{:08b}'.format(121)
'01111001'
>>> '{:08b}'.format(7)
'00000111'

UPDATE

As suggested by Martijn Pieters, the builtin format function is far superior:

>>> format(121, '08b')
'01111001'
>>> format(7, '08b')
'00000111'

UPDATE 2

Just realized this question was marked as a duplicate. Pieters gave the format answer here, and explains how it works in detail.

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
  • 2
    Don't use `str.format()` where you can use the [`format()` function](https://docs.python.org/3/library/functions.html#format). Why add the parsing overhead? `format(121, '08b')` produces the same output without Python having to find the placeholder and pulling the formatting instruction out. You have just *one* placeholder and no other text in that template string. – Martijn Pieters Jul 20 '17 at 07:17
  • How did I not know about this builtin function? I thought I knew them all. Wow, thanks! – Ray Toal Jul 20 '17 at 15:23