Python Program to Convert Bytes to a String
Convert bytes to a string python
In this example, you will learn to convert bytes to a string.
To understand this example, you should have the knowledge of the following Python programming topics
Example :
print(b'Easy \xE2\x9C\x85'.decode("utf-8"))
Output : Easy
In Python 3, the default encoding is "utf-8"
, so you can directly use:
b'hello devloper'.decode()
or in other similar way
b'hello devloper'.decode(encoding="utf-8")
bytes.
decode
(encoding='utf-8', errors='strict')bytearray.
decode
(encoding='utf-8', errors='strict')
Return a string decoded from the given bytes. Default encoding is 'utf-8'
. errors may be given to set a different error handling scheme. The default for errors ;is ;'strict'
, meaning that encoding errors raise a ;UnicodeError
. Other possible values are 'ignore'
, 'replace'
and any other name registered via codecs.register_error()
, see section Error Handlers. For a list of possible encodings, see section Standard Encodings.
By default, the errors argument is not checked for best performances, but only used at the first decoding error. Enable the Python Development Mode, or use a debug build to check errors.
Note : Passing the encoding argument tostr
& allows decoding any bytes-like object directly, without needing to make a temporary bytes or bytearray object.