In Python, you can easily obtain the binary representation of a string using various methods.
<code class="python">st = "hello world" binary_rep = ' '.join(format(ord(x), 'b') for x in st) print(binary_rep)</code>
This method iterates over each character in the string, converts its Unicode code point to an integer, then formats it into a binary representation using the format function.
<code class="python">st = "hello world" binary_rep = ' '.join(format(x, 'b') for x in bytearray(st, 'utf-8')) print(binary_rep)</code>
This method converts the string to a bytearray (an array of bytes), then formats each byte into a binary representation. This method considers specific encoding (e.g., 'utf-8' in this case) and handles non-ASCII characters appropriately.
The above is the detailed content of How to Convert a String to Binary Representation in Python?. For more information, please follow other related articles on the PHP Chinese website!