Home > Backend Development > Python Tutorial > How Do I Decode Bytes to a String in Python 3?

How Do I Decode Bytes to a String in Python 3?

Barbara Streisand
Release: 2024-12-18 03:08:10
Original
801 people have browsed it

How Do I Decode Bytes to a String in Python 3?

Decoding Bytes to String in Python 3

In Python, bytes objects represent binary data, while strings hold textual information. If you've acquired a bytes object from an external source, such as the standard output of a program, you may need to convert it to a string for processing or display.

In Python 3, you can utilize the decode() method to convert a bytes object into a string:

bytes_object = b'binary data'
string = bytes_object.decode("encoding")
Copy after login

Where "encoding" represents the encoding of the bytes object. For instance, if the data is encoded in UTF-8, you would use:

bytes_object.decode("utf-8")
Copy after login

Example:

Consider the following output from the ls command, captured as a bytes object:

>>> from subprocess import *
>>> stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
Copy after login

To convert this bytes object to a printable string, we can use:

stdout_string = stdout.decode("utf-8")
print(stdout_string)
Copy after login

The above is the detailed content of How Do I Decode Bytes to a String in Python 3?. 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