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: bytes is 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 is strict. It means that the UnicodeError will be raised. Some other values are ignore and replace.

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.

ASCII Table For Codes
# String of encoded codes
# For word EDPRESSO
bytes= b'\x45\x44\x50\x52\x45\x53\x53\x4f'
# Using encoding scheme: UTF8
bytes= bytes.decode('utf8')
# Show results
print ("Decoded bytes: " + bytes)

Explanation

  • Line 3: We encode string, cast to byte object.
  • Line 5: We use the decode() method with utf8 encoding scheme to transform from encoded values to a string object.
  • Line 7: We print decoded values.

Example 2

# String of encoded codes
# For word EDPRESSO
bytes= b'\x49\x20\x4c\x6f\x76\x65\x20\x45\x64\x75\x63\x61\x74\x69\x76\x65\x21'
# Using encoding scheme: UTF8
bytes= bytes.decode(encoding='utf-8', errors='strict')
# Show results
print (bytes)

Explanation

  • Line 3: We encode string, cast to byte object.
  • Line 5: We call the decode() method with utf-8 encoding scheme and strict as error handler to transform from encoded values to a string object.
  • Line 7: We print decoded values.