Python decode()函数

Python decode()函数教程

Python 字符串 decode() 函数,以 encoding 指定的编码格式解码 字符串, decode() 函数还可以通过 errors 参数可以指定不同的错误处理方案。

Python decode()函数详解

语法

str.decode(encoding='UTF-8',errors='strict')

参数

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

错误处理方式

错误处理方式 说明
strict 遇到非法字符就抛出异常
ignore 忽略非法字符
replace 用“?”替换非法字符
xmlcharrefreplace 使用 xml 的字符引用

返回值

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

案例

decode()解码字符串

使用 decode() 函数,解码字符串

print("嗨客网(www.haicoder.net)") # 使用 decode() 函数,进行解码 strHaicoder = "嗨客网(HaiCoder)" byteRes = strHaicoder.encode() strRes = byteRes.decode() print("byteRes =", byteRes) print("strRes =", strRes)

程序运行后,控制台输出如下:

98 python字符串decode.png

首先,我们定义了一个字符串 变量 strHaicoder,接着我们使用字符串的 encode() 函数,先对该变量进行编码,并返回 bytes 类型的变量,接着又对该 bytes 变量进行编码。

最后,我们发现对 encode() 函数编码返回的字符串进行重新的解码后,又返回了原字符串。

decode()解码字符串指定格式

使用 decode() 函数,按指定格式解码字符串

print("嗨客网(www.haicoder.net)") # 使用 decode() 函数,按指定格式解码字符串 strHaicoder = "嗨客网(HaiCoder)" byteRes = strHaicoder.encode('gbk') strRes = byteRes.decode('gbk') print("byteRes =", byteRes) print("strRes =", strRes)

程序运行后,控制台输出如下:

99 python字符串decode.png

首先,我们定义了一个字符串变量 strHaicoder,接着我们使用字符串的 encode() 函数,先对该变量进行编码,并返回 bytes 类型 的变量,接着又对该 bytes 变量进行编码,同时,我们在编码的时候指定了编码格式为 gbk,解码时使用相同的解码格式。

最后,我们发现对 encode() 函数编码返回的字符串进行重新的解码后,又返回了原字符串。

decode()解码字符串指定错误模式

使用 decode() 函数,解码字符串指定错误模式

print("嗨客网(www.haicoder.net)") # 使用 decode() 函数,解码字符串指定错误模式 strHaicoder = "嗨客网(HaiCoder)" byteRes = strHaicoder.encode('gbk') strRes = byteRes.decode('gbk', 'strict') print("byteRes =", byteRes) print("strRes =", strRes)

程序运行后,控制台输出如下:

100 python字符串decode.png

首先,我们定义了一个字符串变量 strHaicoder,接着我们使用字符串的 encode() 函数,先对该变量进行编码,并返回 bytes 类型的变量,接着又对该 bytes 变量进行编码,同时,我们在编码的时候指定了编码格式为 gbk,解码时使用相同的解码格式,并指定错误模式。

最后,我们发现对 encode() 函数编码返回的字符串进行重新的解码后,又返回了原字符串。

Python decode()函数总结

Python 字符串 decode() 函数,以 encoding 指定的解码格式解码字符串。Python decode() 函数语法:

str.decode(encoding='UTF-8',errors='strict')