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

How Do I Convert a Bytes Object to a String in Python 3?

DDD
Release: 2024-12-26 02:49:11
Original
632 people have browsed it

How Do I Convert a Bytes Object to a String in Python 3?

Converting Bytes to a String in Python 3

Problem:

You have captured the standard output of an external program into a bytes object and need to display it as a string. For example:

import subprocess
p = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE)
stdout, _ = p.communicate()
Copy after login

This will result in a bytes object like:

b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1\n' 
Copy after login

Your goal is to convert this bytes object into a standard Python string.

Solution:

To convert a bytes object stdout to a string in Python 3, use the decode() method. This method takes the encoding of the bytes object as an argument. Here's how to do it:

decoded_stdout = stdout.decode("encoding")
Copy after login

Choosing the Encoding:

The encoding parameter specifies the character set used to decode the bytes. In the example given, UTF-8 is assumed as the default encoding. However, it's important to use the actual encoding of your data.

If you don't know the encoding, you can try using "utf-8". Alternatively, you can use a library like chardet to detect the encoding automatically.

Example:

Using UTF-8 as the assumed encoding:

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

You can now print your decoded string:

print(decoded_stdout) 
# Output:
# -rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1
Copy after login

The above is the detailed content of How Do I Convert a Bytes Object 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template