What is bytes.decode() in Python?
Overview
bytes.decode() is used to decode bytes to a string object. Decoding to a string object depends on the specified arguments. It also allows us to mention an error handling scheme to use for seconding errors.
Note:
bytesis a built-in binary sequence type in Python. It is used for binary data manipulation.
Syntax
bytes.decode(encoding='utf-8', errors='strict')
Parameters
encoding: This shows the encoding scheme to be used. For example,ascii,utf8, or others.error: This shows the error handling scheme that will be used. It must be defined accordingly. The default value of this parameter isstrict. It means that theUnicodeErrorwill be raised. Some other values areignoreandreplace.
Note: To read more about error handles, click here.
Return value
It will return decoded bytes as a string object.
Example 1
Let’s look at an example to see how the bytes.decode() method works.
# String of encoded codes# For word EDPRESSObytes= b'\x45\x44\x50\x52\x45\x53\x53\x4f'# Using encoding scheme: UTF8bytes= bytes.decode('utf8')# Show resultsprint ("Decoded bytes: " + bytes)
Explanation
- Line 3: We encode string, cast to
byteobject. - Line 5: We use the
decode()method withutf8encoding scheme to transform from encoded values to astringobject. - Line 7: We print decoded values.
Example 2
# String of encoded codes# For word EDPRESSObytes= b'\x49\x20\x4c\x6f\x76\x65\x20\x45\x64\x75\x63\x61\x74\x69\x76\x65\x21'# Using encoding scheme: UTF8bytes= bytes.decode(encoding='utf-8', errors='strict')# Show resultsprint (bytes)
Explanation
- Line 3: We encode string, cast to
byteobject. - Line 5: We call the
decode()method withutf-8encoding scheme andstrictas error handler to transform from encoded values to astringobject. - Line 7: We print decoded values.