Converting Strings to Binary in Python
The task of converting a string to its binary representation arises frequently in various programming scenarios. Python provides several approaches to achieve this transformation efficiently.
One straightforward method involves utilizing a comprehension to iterate over the string characters and convert each character's ASCII code into its binary representation. The format function with the 'b' format specifier can be employed to achieve this:
<code class="python">def toBinary(string): return ' '.join(format(ord(x), 'b') for x in string)</code>
Alternatively, Python's bytearray can handle binary data. By creating a bytearray object from the string, you can directly obtain the binary representation of each character:
<code class="python">def toBinary(string): return ' '.join(format(x, 'b') for x in bytearray(string, 'utf-8'))</code>
Both techniques produce similar outputs, providing the binary representation of the input string as a space-separated binary string.
The above is the detailed content of How Can I Convert a String to Binary in Python?. For more information, please follow other related articles on the PHP Chinese website!