Python3 encode()方法
目录
描述
Python encode() 方法以指定的编码格式编码字符串。errors 参数可以指定不同的错误处理方案。
语法
encode()
方法语法:
str.encode(encoding='UTF-8',errors='strict')
参数
- encoding — 要使用的编码,如: UTF-8。
- errors — 设置不同错误的处理方案。默认为 ‘
strict
‘,意为编码错误引起一个UnicodeError
。 其他可能得值有 ‘ignore
‘, ‘replace
‘, ‘xmlcharrefreplace
‘, ‘backslashreplace
‘ 以及通过codecs.register_error()
注册的任何值。
返回值
该方法返回编码后的字符串,它是一个 bytes
对象。
实例
以下实例展示了encode()
方法的实例:
#!/usr/bin/python3 str = "码云笔记"; str_utf8 = str.encode("UTF-8") str_gbk = str.encode("GBK") print(str) print("UTF-8 编码:", str_utf8) print("GBK 编码:", str_gbk) print("UTF-8 解码:", str_utf8.decode('UTF-8','strict')) print("GBK 解码:", str_gbk.decode('GBK','strict'))
以上实例输出结果如下:
码云笔记 UTF-8 编码: b'\xe7\xa0\x81\xe4\xba\x91\xe7\xac\x94\xe8\xae\xb0' GBK 编码: b'\xc2\xeb\xd4\xc6\xb1\xca\xbc\xc7' UTF-8 解码: 码云笔记 GBK 解码: 码云笔记
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » Python3 encode()方法
码云笔记 » Python3 encode()方法