W3docs

Convert bytes to a string

To convert a byte object into a string, you can use the decode() method.

To convert a byte object into a string, you can use the decode() method. This method is available on all bytes objects, and takes an encoding as its argument. For example:

Convert a byte object into a string using the decode() method in Python

byte_string = b'Hello, world!'
string = byte_string.decode('utf-8')
print(string)  # Output: 'Hello, world!'

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

You can also use the str() function to accomplish this. For example:

Convert a byte object into a string using the str() method in Python

byte_string = b'Hello, world!'
string = str(byte_string, 'utf-8')
print(string)  # Output: 'Hello, world!'

Both of these approaches assume that the byte string is encoded using the utf-8 encoding. If the byte string was encoded using a different encoding, you will need to specify the correct encoding when calling decode() or str().