Convert String to Binary in Python
In Python, there are multiple ways to convert a string to its binary representation.
Using the 'ord' Function:
This approach uses the ord() function to get the Unicode code point for each character in the string. The code points are then converted to binary using the format() function.
<code class="python">import functools def toBinary(st): return ' '.join(format(ord(x), 'b') for x in st)</code>
Using 'bytearray':
Alternatively, you can use Python's bytearray class to represent the string as a sequence of bytes. Each byte can then be converted to binary using the format() function.
<code class="python">def toBinary(st): return ' '.join(format(x, 'b') for x in bytearray(st, 'utf-8'))</code>
Here's an example:
<code class="python">st = "hello world" print(toBinary(st)) # OR print(' '.join(format(ord(x), 'b') for x in st)) # Output: 1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100</code>
The above is the detailed content of How to Convert a String to Binary in Python?. For more information, please follow other related articles on the PHP Chinese website!