How to Convert Bytes to String in Python
To convert the data type bytes to a string in Python, use the .decode()
function and set the encoding in the first argument, which will most likely be utf-8.
byte_str = b'abcde'
string = byte_str.decode("utf-8")
print(string)
type(string)
type(byte_str)
abcde
str
bytes
In the example above we have converted the data type bytes to str with utf-8 encoding.
Note – .decode()
does not modify the original variable so you will need to store the result in a new one.