TechieClues
Updated date Mar 24, 2024
In this blog, we will see how to convert a string to binary in python
• 4.2k
• 0
• 0

How to Convert a String to Binary in Python?

The binary is a base-2 number system that represents data using only two digits, typically 0 and 1. It is used in computers and other electronic devices to store and transmit information. We will use below methods to convert a string to binary.

Method 1: Using the bin() function

To convert a string to binary in Python, use the built-in bin() function. This function takes an integer or a string as an argument and returns its binary representation as a string prefixed with "`0b`".

``````str = "Hello, World!"
binary = ''.join(format(ord(i), '08b') for i in str)
print(binary)``````

Output:

``01001000 01100101 01101100 01101100 01101111 00101100 00100000 01010111 01101111 01110010 01101100 01100100 00100001``

Method 2: Using the bytearray() function

To convert a string to binary in Python is to use the `bytearray()` function. This function takes a string as an argument and returns a bytearray object that represents the string as a sequence of bytes. Each byte is represented as an integer between 0 and 255.

``````str = "Hello, World!"
binary = ''.join(format(byte, '08b') for byte in bytearray(str, encoding='utf-8'))
print(binary)``````

Output:

``01001000 01100101 01101100 01101100 01101111 00101100 00100000 01010111 01101111 01110010 01101100 01100100 00100001``

Method 3: Using the struct.pack() function

The struct module in Python provides a powerful set of functions to convert between binary data and Python objects. The pack() function in this module can be used to convert a string to binary. This function takes a format string and one or more arguments and returns a string containing the binary representation of the arguments.

``````import struct

str = "Hello, World!"
binary = ''.join(format(byte, '08b') for byte in struct.pack('!{}s'.format(len(str)), str.encode()))
print(binary)``````

Output:

``01001000 01100101 01101100 01101100 01101111 00101100 00100000 01010111 01101111 01110010 01101100 01100100 00100001``

Method 4: Using the ord() function and bitwise operations

To convert a string to binary in Python is to use the ord() function and bitwise operations. This method involves converting each character in the string to its ASCII value using the `ord()` function, and then using bitwise operations to obtain its binary representation.

``````str = "Hello, World!"
binary = ''.join(format(ord(i), '08b') for i in str)
print(binary)``````

Output:

``01001000 01100101 01101100 01101100 01101111 00101100 00100000 01010111 01101111 01110010 01101100 01100100 00100001``