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()
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'
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")
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")
You can now print your decoded string:
print(decoded_stdout) # Output: # -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1
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!