Python3 bytes.decode() Method
Description
The decode() method decodes a bytes object using the specified encoding. The default encoding is 'utf-8'.
Syntax
Syntax of the decode() method:
bytes.decode(encoding="utf-8", errors="strict")
Parameters
- encoding -- the encoding to use, such as "UTF-8".
- errors -- sets different error handling schemes. Defaults to 'strict', meaning an encoding error raises a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace', and any value registered through codecs.register_error().
Return Value
This method returns the decoded string.
Example
The following example demonstrates the decode() method:
Example (Python 3.0+)
#!/usr/bin/python3
str
=
"
Runoob Tutorial
"
;
str_utf8
=
str
.
encode
(
"
UTF-8
"
)
str_gbk
=
str
.
encode
(
"
GBK
"
)
(
str
)
(
"
UTF-8 encoding:
"
,
str_utf8
)
(
"
GBK encoding:
"
,
str_gbk
)
(
"
UTF-8 decoding:
"
,
str_utf8
.
decode
(
'
UTF-8
'
,
'
strict
'
)
)
(
"
GBK decoding:
"
,
str_gbk
.
decode
(
'
GBK
'
,
'
strict
'
)
)
The output of the above example is:
Runoob Tutorial
UTF-8 编码: b'\xe8\x8f\x9c\xe9\xb8\x9f\xe6\x95\x99\xe7\xa8\x8b'
GBK 编码: b'\xb2\xcb\xc4\xf1\xbd\xcc\xb3\xcc'
UTF-8 解码: Runoob Tutorial
GBK 解码: Runoob Tutorial
Python3 Strings