Home >Backend Development >Python Tutorial >How Can I Convert Bytes to a String in Python 3?
This question arises when handling data captured from external programs or input streams. We want to encode such data as regular Python strings for printing or further processing.
Consider the following bytes object:
>>> from subprocess import * >>> stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] >>> stdout b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n'
To convert it to a string for printing purposes, decode the bytes using the appropriate encoding:
>>> stdout.decode("utf-8") '-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n'
While UTF-8 is a common encoding, it is essential to use the encoding that matches the actual data. Failure to do so may result in garbled or incorrect output.
The above is the detailed content of How Can I Convert Bytes to a String in Python 3?. For more information, please follow other related articles on the PHP Chinese website!