How to Convert a String to Binary Representation in Python?

Susan Sarandon
Release: 2024-10-25 02:31:02
Original
160 people have browsed it

How to Convert a String to Binary Representation in Python?

Converting String to Binary Representation in Python

In Python, you can easily obtain the binary representation of a string using various methods.

Method 1: Using Formatted String

<code class="python">st = "hello world"
binary_rep = ' '.join(format(ord(x), 'b') for x in st)
print(binary_rep)</code>
Copy after login

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.

Method 2: Using Bytearray

<code class="python">st = "hello world"
binary_rep = ' '.join(format(x, 'b') for x in bytearray(st, 'utf-8'))
print(binary_rep)</code>
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!