Home  >  Article  >  Backend Development  >  How to Convert a String to Binary in Python?

How to Convert a String to Binary in Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-25 05:59:02823browse

How to Convert a String to Binary in Python?

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!

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