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.

Download  Run Code

 
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.

Download  Run Code

 
To get a list of binary strings, you can use the list constructor:

Download  Run Code

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:

Download  Run Code

 
To get a list, you can use the list constructor:

Download  Run Code

That’s all about converting a string to binary in Python.