HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCritical

Convert bytes to a string in Python 3

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
stringconvertbytespython

Problem

I captured the standard output of an external program into a 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'


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

>>> print(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


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

See Best way to convert string to bytes in Python 3? for the other way around.

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!

Code Snippets

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

Context

Stack Overflow Q#606191, score: 5874

Revisions (0)

No revisions yet.