Python: 3 Ways to Convert a String to Binary Codes

Updated: June 1, 2023 By: Khue Post a comment

Binary codes (binary, binary numbers, or binary literals) are a way of representing information using only two symbols: 0 and 1. They are like a secret language that computers are able to understand. By combining these symbols in different patterns, we can represent numbers, letters, and other data.

This concise, example-based article will walk you through 3 different approaches to turning a given string into binary in Python.

Using the ord() function and string formatting

What we’ll do are:

  1. Loop through each character in the string.
  2. Convert each character to its corresponding Unicode code using the ord() function.
  3. Convert the Unicode code to binary using the format() function with a format specifier.
  4. Concatenate the binary codes to form the final binary string.

Code example:

input = "Sling Academy"
binary_codes = ' '.join(format(ord(c), 'b') for c in input)
print(binary_codes)

Output:

1010011 1101100 1101001 1101110 1100111 100000 1000001 1100011 1100001 1100100 1100101 1101101 1111001

Using the bytearray() function

Here’re the steps:

  1. Convert the string to a bytearray object, which represents the string as a sequence of bytes.
  2. Iterate over each byte in the bytearray.
  3. Convert each byte to binary using the format() function with a format specifier.
  4. Concatenate the binary codes to form the final binary string.

Code example:

my_string = "Sling Academy"
byte_array = bytearray(my_string, encoding='utf-8')
binary_codes = ' '.join(bin(b)[2:] for b in byte_array)
print(binary_codes)

Output:

1010011 1101100 1101001 1101110 1100111 100000 1000001 1100011 1100001 1100100 1100101 1101101 1111001

Using the bin() and ord() functions

This technique can be explained as follows:

  1. Iterate over each character in the string.
  2. Convert each character to its corresponding Unicode code using the ord() function.
  3. Use the bin() function to convert the Unicode code to binary.
  4. Remove the leading 0b prefix from each binary code.
  5. Concatenate the binary codes to form the final binary string.

Thanks to Python’s concise syntax, our code is very succinct:

text = "Sling Academy"
binary_string = ' '.join(bin(ord(char))[2:] for char in text)
print(binary_string)

Output:

1010011 1101100 1101001 1101110 1100111 100000 1000001 1100011 1100001 1100100 1100101 1101101 1111001

Conclusion

You’ve learned some methods to transform a given string into binary in Python. All of them are neat and delicate. Choose the one you like to go with. Happy coding & have a nice day!