Convert String to Binary in Python



In this article, we are going to learn about converting a string to binary, which means representing each character in the string using the binary digits 0 and 1.

A binary number is a number expressed in the base2 numerical system, which uses only two symbols - 0 and 1. Since computers store data as binary, converting the strings into binary helps to understand how data is stored or transmitted. Python provides several methods to achieve this.

Using Python ord() and format() Functions

The first approach is by using the Python ord() and format(), Where the Python ord() function is used to retrieve the integer representing the Unicode code point of a given character and the Python format() function is used to return the given value in the specified format based on the formatter.

Example

Let's look at the following example, where we are going to convert the characters of the string to its ASCII value using the ord() function and then format it into an 8-bit binary using the format() function.

str1 = "TP"
result = ' '.join(format(ord(char), '08b') for char in str1)
print(result)

The output of the above program is as follows -

01010100 01010000

Using Python bytearray() and bin() Functions

The second approach is by using the Python bytearray() function and bin() function, while the Python bytearray() function is used to return the new array with bytes and the Python bin() function is used to convert a given integer to its binary equivalent, which is represented as a string.

Example

Consider the following example, where we are going to convert the string into a byte array and then apply the bin() function to get the binary strings for each byte.

str1 = "Hello"
result = ' '.join(bin(byte)[2:].zfill(8) for byte in bytearray(str1, 'utf-8'))
print(result)

The following is the output of the above program -

01001000 01100101 01101100 01101100 01101111

Using Python List Comprehension

In this approach, we are going to use the List Comprehension with the ord() function and bin(). The Python list comprehension offers a simple way to create a list using a single line of code. It combines loops and conditional statements, making it efficient compared to the traditional methods of list construction.

Example

In the following example, we are going to use the list comprehension to convert each character to its ASCII code, then to binary by using the bin() function.

str1 = "AB"
x = [bin(ord(char))[2:].zfill(8) for char in str1]
result = ' '.join(x)
print(result)

The output of the above program is as follows -

01000001 01000010
Updated on: 2025-05-20T13:15:34+05:30

870 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements