Convert bytes to a string

Total
0
Shares

I captured the standard output of an external program into a bytes object:

>>> from subprocess import *
>>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
>>>
>>> command_stdout
b'total 0n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2n'

I want to convert that to a normal Python string, so that I can print it like this:

>>> print(command_stdout)
-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1
-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2

I tried the binascii.b2a_qp() method, but got the same bytes object again:

>>> binascii.b2a_qp(command_stdout)
b'total 0n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2n'

How do I convert the bytes object to a str with Python 3?


Solution

Decode the bytes object to produce a string:

>>> b"abcde".decode("utf-8") 
'abcde'

The above example assumes that the bytes object is in UTF-8, because it is a common encoding. However, you should use the encoding your data is actually in!

Source: StackOverflow.com

Leave a Reply

Your email address will not be published. Required fields are marked *