icon

Convert String to Binary in Python

Last modified: 2023-08-29

Conversion

For converting strings to binary, we need to convert each character to binary by first converting the character to Unicode.
Then concatenate these binaries.

text = "Hello"

bin_str = ""
for c in text:
    c_bin = bin(ord(c))[2:] # remove "0b" prefix
    bin_str += c_bin.zfill(8) # padding to 8-bit for adjustment

print(bin_str)
# 0100100001100101011011000110110001101111