Python/ref string encode
来自菜鸟教程
<languages />
Python字符串encode()方法
例
UTF-8编码字符串:
txt = "My name is Ståle" x = txt.encode() print(x)
定义和用法
The
encode()
方法使用指定的编码对字符串进行编码。如果未指定编码,则将使用UTF-8。
句法
string.encode(encoding=encoding, errors=errors)
参数值
| 参数 | 描述 | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| encoding | 可选的。一个字符串,指定要使用的编码。默认为UTF-8 | ||||||||||||
| errors |
可选的。一个字符串,指定错误方法。合法值包括:
|
更多例子
例
这些示例使用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"))