String to Binary Sequence in Python

In this python example, we are going to convert string to binary sequences. Each character in the string is converted to 8-bit ASCII code using python’s built-in function bin() and ord() function, after that, we concatenate them to produce a single binary sequence.

Python Source Code


def get_binary(string):
    binary_plain_text = ''
    for ch in string:
        binary_plain_text += bin(ord(ch))[2:].zfill(8)
    return binary_plain_text

print(get_binary("Hi!"))

The output of the above program is:

010010000110100100100001

Above program can be implemented in python one liner as follows:

String to Binary One Liner


# Convert string to binary
string = "Hi!"
binary = ''.join('{0:08b}'.format(ord(x), 'b') for x in string)
print(binary)

The output of the above program is:

010010000110100100100001