Python encode()函数

Python encode()函数教程

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

Python encode()函数详解

语法

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

参数

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

错误处理方式

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

返回值

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

案例

encode编码字符串

使用 encode() 函数,编码字符串

print("嗨客网(www.haicoder.net)") # 使用 encode() 函数,编码字符串 strHaicoder = "嗨客网(HaiCoder)" byteRes = strHaicoder.encode() print("byteRes =", byteRes)

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

95 python字符串encode.png

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

最后,我们使用 print() 函数打印编码后的字节数组。

指定encode编码格式

使用 encode() 函数,指定encode编码格式

print("嗨客网(www.haicoder.net)") # 使用 encode() 函数,指定encode编码格式 strHaicoder = "嗨客网(HaiCoder)" byteRes = strHaicoder.encode('gbk') print("byteRes =", byteRes)

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

96 python字符串encode.png

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

最后,我们使用 print() 函数打印编码后的字节数组。

encode编码使用严格模式

使用 encode() 函数,进行编码并使用严格模式

print("嗨客网(www.haicoder.net)") # 使用 encode() 函数,进行编码并使用严格模式 strHaicoder = "嗨客网(HaiCoder)" byteRes = strHaicoder.encode('gbk', 'strict') print("byteRes =", byteRes)

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

97 python字符串encode.png

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

最后,我们使用 print() 函数打印编码后的字节数组。

Python encode()函数总结

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

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