The decode() function converts from one encoding format, in which the argument string is encoded, to the desired encoding format.
Python Bytes to String
To convert bytes to strings in Python, use the decode() method to produce a string from a byte object. The String decode() is a built-in method that decodes the string using the codec registered for encoding.
The decode() method takes an argument which is the codec utf-8. It can be another codec, but we will use this as this is the standard.
It would help if you use utf-8 encoding because it is very common, but you need to use the encoding your data is actually in.
Syntax
decode(encoding, error)
Parameters
encoding: The encoding parameter defines the encoding based on which decoding has to be performed.
error: The error parameter determines how to handle the errors if they occur, e.g., ‘strict‘ raises Unicode error.
Return Value
It returns the original string from the decoded string.
Example
To convert from bytes object to a string, follow the below two steps.
Step 1: Convert Original String to a bytes object
This step is only necessary if you don’t have a bytes object. If you have a bytes object, you don’t need to perform this step.
Let’s first encode the string into a bytes object.
# app.py str1 = "Hello and welcome to the world of pythön!" str2 = str1.encode() print(str2)
Output
python3 app.py b'Hello and welcome to the world of pyth\xc3\xb6n!'
To check the data type of str2, use the type() method.
str1 = "Hello and welcome to the world of pythön!" str2 = str1.encode('utf-8') print(type(str2))
Output
<class 'bytes'>
You can see that we now have a bytes object. Now, we will convert the bytes object to String.
Step 2: Convert from bytes object to String.
To convert bytes object to the original string, use the decode() method with the exact encoding mechanism. We used utf-8 style encoding, so you need to use the same type of decoding as well.
# app.py str1 = "Hello and welcome to the world of pythön!" str2 = str1.encode('utf-8') print(type(str2)) print(str2) print('After converting from bytes to string') str3 = str2.decode('utf-8') print(type(str3)) print(str3)
Output
python3 app.py <class 'bytes'> b'Hello and welcome to the world of pyth\xc3\xb6n!' After converting from bytes to string <class 'str'> Hello and welcome to the world of pythön!
You can see that the decode() method successfully decodes the bytes object to String.
That’s it.