Python convert a byte object to string:
Previously, we learned how to convert a string to byte object in python. In this post, we will do the reverse of it, i.e. converting a byte object to a string. It is also called decoding.
We are using python 3 in this example.
Using decode():
decode method is defined in the bytes class. For example:
byte_string = b'Hello World \xF0\x9F\x98\x81'
decoded_str = byte_string.decode('UTF-8')
print(decoded_str)
If you run it, it will print the below:
Hello World 😁
Here,
- byte_string is a byte object.
- decoded_string is a string created by decoding the byte_string using decode. byte_string was encoded using utf-8, so we are passing UTF-8 to decode.
Using str():
We can pass the byte string as first argument to str and the encoding name as the second argument to decode a byte string.
byte_string = b'Hello World \xF0\x9F\x98\x81'
decoded_str = str(byte_string, 'UTF-8')
print(decoded_str)
It will print the same output.