Home >Backend Development >Python Tutorial >How Do I Decode Bytes to a 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")
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")
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]
To convert this bytes object to a printable string, we can use:
stdout_string = stdout.decode("utf-8") print(stdout_string)
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!