Python 中的 encode() 函数有助于将给定字符串转换为编码格式。如果未指定编码,则默认使用 UTF-8。
string.encode(encoding='UTF-8',errors='strict') #where encodings being utf-8, ascii, etc
encode() 函数接受两个可选参数。其中参数 errors 可以是以下六种类型之一。
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| encoding(编码) | 要编码的字符串的编码类型 | 可选 |
| errors(错误处理) | 编码失败时的响应 | 可选 |
默认情况下,函数使用 utf-8 编码,如果发生任何失败,它会引发 UnicodeDecodeError 异常。
| 输入 | 返回值 |
|---|---|
| 字符串 | 编码字符串 |
# unicode string
string = 'pythön!'
# print string
print('The original string is:', string)
# default encoding to utf-8
string_utf8 = string.encode()
# print result
print('The encoded string is:', string_utf8)
输出
The original string is: pythön! The encoded string is: b'pyth\xc3\xb6n!'
# unicode string
string = 'pythön!'
# print string
print('The original string is:', string)
# ignore error
print('The encoded string (with ignore) is:', string.encode("ascii", "ignore"))
# replace error
print('The encoded string (with replace) is:', string.encode("ascii", "replace"))
输出
The original string is: pythön! The encoded string (with ignore) is: b'pythn!' The encoded string (with replace) is: b'pyth?n!'