DEV Community

loading...
Cover image for Python Bytes to string

Python Bytes to string

courseprobe profile image Course Probe ・2 min read

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()[0]
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Example 1:

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'
Enter fullscreen mode Exit fullscreen mode

Example 2:

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)
Enter fullscreen mode Exit fullscreen mode

or

unicode('hello', encoding)
Enter fullscreen mode Exit fullscreen mode

On Python 3

encoding = 'utf-8'
b'hello'.decode(encoding)
Enter fullscreen mode Exit fullscreen mode

or

str(b'hello', encoding)
Enter fullscreen mode Exit fullscreen mode

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:

Python 3 Masterclass step by step with coding exercises

Get the book: How to learn to program in python

Reference links:


Other Dev Posts:

Discussion (0)

pic
Editor guide