Python 字符串 encode() 方法
定义和用法
encode() 方法使用指定的编码对字符串进行编码。如果未指定编码,则将使用 UTF-8。
实例
例子 1
对字符串进行 UTF-8 编码:
txt = "My name is Ståle" x = txt.encode() print(x)
例子 2
这些示例使用 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"))
语法
string.encode(encoding=encoding, errors=errors)
参数
| 参数 | 描述 |
|---|---|
| encoding | 可选。字符串。规定要使用的编码。默认是 UTF-8。 |
| errors |
可选。字符串。规定错误方法。合法值是:
|