Introduction:
Converting strings to their binary representations is a common task in computer science. This article explores different methods in Python to achieve this functionality.
Method 1: Using Format Strings
Using format strings, you can convert each character of the string into its binary representation. The following code snippet demonstrates this:
<code class="python">st = "hello world" binary_string = ' '.join(format(ord(x), 'b') for x in st) print(binary_string)</code>
This approach produces the following result:
1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100
Method 2: Using bytearray
The bytearray class in Python provides a more concise way to convert strings to binary. It automatically encodes the string using UTF-8 encoding. The following code demonstrates this:
<code class="python">st = "hello world" binary_string = ' '.join(format(x, 'b') for x in bytearray(st, 'utf-8')) print(binary_string)</code>
This method produces the same output as the previous approach.
The above is the detailed content of Here are a few question-based titles that fit the content of your article: * **How to Convert a String to Binary in Python: Two Simple Methods** * **String to Binary Conversion in Python: Format Stri. For more information, please follow other related articles on the PHP Chinese website!