In this short tutorial, let’s explore different ways to convert bytes to string in python, depending on the kind of project you are running you might need to find a way to decode bytes to strings in python, so let’s explore some examples below.
Let’s say you get some standard output from an external program:
>>> from subprocess import * >>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()
And you get an array of bytes returned by the communicate() method.
>>> command_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'
Now imagine you need the output as a regular python strin, so you can print something like:
>>> 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
You need to decode the bytes object to produce a string:
>>> b"abcde" b'abcde' # utf-8 is used here because it is a very common encoding, but you # need to use the encoding your data is actually in. >>> b"abcde".decode("utf-8") 'abcde'
You need to decode the byte string and turn it in to a character (Unicode) string.
On Python 2
encoding = 'utf-8' 'hello'.decode(encoding)
On Python 3
encoding = 'utf-8' b'hello'.decode(encoding)
Hope this short tutorial has been useful, if you are looking for additional resources to learn python you can take a look at the below:
Get the book: How to learn to program in python
Other Dev Posts: