Convert bytes to string in Python
There are several ways to convert a bytes value into a string in Python. Some of them are shown below:
The str() Method
The built-in str() method of Python can convert a bytes value into a string:
Example:
text_bytes = bytes("Hello world","utf-8")
text_string = str(text_bytes, "utf-8")
print(text_string)
print(type(text_string))
Output:
Hello world
<class 'str'>
<class 'str'>
The decode() String Method
The String decode() method of Python can also convert a bytes value into a string:
Example:
text_bytes = bytes("Hello world","utf-8")
text_string = text_bytes.decode()
print(text_string)
print(type(text_string))
Output:
Hello world
<class 'str'>
<class 'str'>
The decode() Method of codecs Module
The decode() method from the built-in codecs module of Python can also be used to convert a bytes value into a string:
Example:
import codecs
text_bytes = bytes("Hello world","utf-8")
text_string = codecs.decode(text_bytes)
print(text_string)
print(type(text_string))
Output:
Hello world
<class 'str'>
<class 'str'>