Python bytes decode() 方法

描述

bytes decode() 方法以指定的编码格式解码 bytes 对象,默认编码为 'utf-8'。

对应的编码方法:encode() 方法 。

语法

Python bytes decode() 方法语法:

B.decode([encoding="utf-8"][,errors="strict"])

参数

  • encoding -- 可选参数,要使用的编码,默认编码为 'utf-8'。
  • errors -- 可选参数,设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值。

返回值

该方法返回解码后的字符串。

实例

以下实例展示了 bytes decode() 方法的实例:

#!/usr/bin/python3

S = "菜鸟教程";
S_utf8 = S.encode("UTF-8")
S_gbk = S.encode("GBK")

print(S)

print("UTF-8 编码:", S_utf8)
print("GBK 编码:", S_gbk)

print("UTF-8 解码:", S_utf8.decode('UTF-8','strict'))
print("GBK 解码:", S_gbk.decode('GBK','strict'))

以上实例输出结果如下:

菜鸟教程
UTF-8 编码: b'xe8x8fx9cxe9xb8x9fxe6x95x99xe7xa8x8b'
GBK 编码: b'xb2xcbxc4xf1xbdxccxb3xcc'
UTF-8 解码: 菜鸟教程
GBK 解码: 菜鸟教程
原文地址:https://www.cnblogs.com/wushuaishuai/p/7686265.html