How to Convert a String to Binary in Python?

Patricia Arquette
Release: 2024-10-25 05:59:02
Original
893 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template