Python 字符串 encode() 方法
实例
对字符串进行 UTF-8 编码:
txt = "My name is Ståle"x = txt.encode()print(x)
定义和用法
encode() 方法使用指定的编码对字符串进行编码。如果未指定编码,则将使用 UTF-8。
语法
string.encode(encoding=encoding, errors=errors)
参数值
| 参数 | 描述 |
|---|---|
| encoding | 可选。字符串。规定要使用的编码。默认是 UTF-8。 |
| errors | 可选。字符串。规定错误方法。合法值是:’backslashreplace’ - 使用反斜杠代替无法编码的字符’ignore’ - 忽略无法编码的字符’namereplace’ - 用解释字符的文本替换字符’strict’ - 默认值,失败时引发错误’replace’ - 用问号替换字符’xmlcharrefreplace’- 用 xml 字符替换字符 |
更多实例
这些示例使用 ascii 编码和无法编码的字符,展示带有不同错误的结果:
txt = "My name is Ståle"print(txt.encode(encoding="ascii",errors="backslashreplace"))print(txt.encode(encoding="ascii",errors="ignore"))print(txt.encode(encoding="ascii",errors="namereplace"))print(txt.encode(encoding="ascii",errors="replace"))print(txt.encode(encoding="ascii",errors="xmlcharrefreplace"))print(txt.encode(encoding="ascii",errors="strict"))