Converting Strings to Binary in Python
In Python, you may encounter the need to represent a string as a sequence of binary digits. This can be useful for various reasons, such as data encryption or binary file manipulation.
Using the bin() Function
The easiest way to convert a string to binary is to use the bin() function. This function takes a string as input and returns its binary representation as a string. For example:
<code class="python">st = "hello world" binary_representation = bin(st) print(binary_representation)</code>
This will output:
0b1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100
However, it is important to note that the bin() function converts the string into a binary representation of its Unicode code points, not its ASCII codes.
Using the bytearray Class
If you want to convert a string to its ASCII binary representation, you can use the bytearray class. Here's an example:
<code class="python">st = "hello world" ascii_binary_representation = ' '.join(format(x, 'b') for x in bytearray(st, 'utf-8')) print(ascii_binary_representation)</code>
This will output:
1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100
The above is the detailed content of How to Convert Strings to Binary in Python: ASCII vs. Unicode?. For more information, please follow other related articles on the PHP Chinese website!