Convert a string to binary in Python
This post will discuss how to convert a string to binary in Python.
1. Using format() function
The idea is to use the ord() function to convert each character of the string to the corresponding integer representing the Unicode code point of that character. Then you can pass that integer to the format() function, which converts it to the number in base 2 when b binary format is used.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': s = "ABC" result = ' '.join(format(ord(c), 'b') for c in s) print(result) # 1000001 1000010 1000011 |
Alternatively, you can iterate over a byte array instead of directly iterating over the string. This can be done using the bytearray() function and avoids using the ord() function.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': s = "ABC" result = ' '.join(format(c, 'b') for c in bytearray(s, "utf-8")) print(result) # 1000001 1000010 1000011 |
To get a list of binary strings, you can use the list constructor:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': s = "ABC" result = list(format(c, 'b') for c in bytearray(s, "utf-8")) print(result) # ['1000001', '1000010', '1000011'] |
2. Using map() function
Another option is to convert the string to an array of bytes using the bytearray() function and then use the bin() function within the map:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': s = "ABC" result = ' '.join(map(bin, bytearray(s, "utf-8"))) print(result) # 0b1000001 0b1000010 0b1000011 |
To get a list, you can use the list constructor:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': s = "ABC" result = list(map(bin, bytearray(s, "utf-8"))) print(result) # ['0b1000001', '0b1000010', '0b1000011'] |
That’s all about converting a string to binary in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)