Home >Backend Development >Python Tutorial >How Can I Convert a String to Binary in Python?

How Can I Convert a String to Binary in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-25 02:55:30320browse

How Can I Convert a String to Binary in Python?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn