Convert bytes to a string
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:
byte_string = b'Hello, world!'
string = byte_string.decode('utf-8')
print(string) # Output: 'Hello, world!'
Watch a video course
Python - The Practical Guide
You can also use the str()
function to accomplish this. For example:
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()
.