Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to 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 base-2 numerical system, which uses only two symbols - 0 and 1. Since computers store data as binary, converting strings into binary helps to understand how data is stored or transmitted. Python provides several methods to achieve this.
Using ord() and format() Functions
The first approach uses the Python ord() and format() functions. The ord() function retrieves the integer representing the Unicode code point of a character, and the format() function formats values based on the specified formatter.
Example
Let's convert each character to its ASCII value using ord() and format it into 8-bit binary using format() ?
text = "TP" result = ' '.join(format(ord(char), '08b') for char in text) print(result)
The output of the above program is as follows ?
01010100 01010000
Using bytearray() and bin() Functions
The second approach uses the Python bytearray() and bin() functions. The bytearray() function returns a new array of bytes, and the bin() function converts an integer to its binary equivalent as a string.
Example
Here we convert the string into a byte array and apply the bin() function to get binary strings for each byte ?
text = "Hello" result = ' '.join(bin(byte)[2:].zfill(8) for byte in bytearray(text, 'utf-8')) print(result)
The following is the output of the above program ?
01001000 01100101 01101100 01101100 01101111
Using List Comprehension
In this approach, we use list comprehension with the ord() and bin() functions. List comprehension offers a simple way to create lists using a single line of code, combining loops and conditional statements efficiently.
Example
We use list comprehension to convert each character to its ASCII code, then to binary using the bin() function ?
text = "AB" binary_list = [bin(ord(char))[2:].zfill(8) for char in text] result = ' '.join(binary_list) print(result)
The output of the above program is as follows ?
01000001 01000010
Comparison
| Method | Functions Used | Best For |
|---|---|---|
ord() + format() |
ord(), format() | Direct formatting control |
bytearray() + bin() |
bytearray(), bin() | UTF-8 encoded strings |
| List comprehension | ord(), bin() | Readable one-liner |
Conclusion
All three methods effectively convert strings to binary representation. Use format() for direct control, bytearray() for UTF-8 encoding, or list comprehension for readable code.
