当前位置:首页 > Python教程 > python进阶

Python3 encode()方法

python3 encode()方法

描述

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()方法的实例:

实例(python 3.0+)

#!/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'))


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!