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.
bytes.decode(encoding='utf-8', errors='strict')
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.
It will return decoded bytes as a string
object.
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)
byte
object.decode()
method with utf8
encoding scheme to transform from encoded values to a string
object.# 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)
byte
object.decode()
method with utf-8
encoding scheme and strict
as error handler to transform from encoded values to a string
object.