Python String encode() 方法
encode()
方法返回给定字符串的编码版本。
示例
title = 'Python Programming'
# 将编码更改为 utf-8
print(title.encode())
# 输出: b'Python Programming'
String encode() 的语法
encode()
方法的语法是:
string.encode(encoding='UTF-8',errors='strict')
String encode() 参数
默认情况下,encode()
方法不需要任何参数。
它返回字符串的 utf-8 编码版本。在失败的情况下,它会引发一个 UnicodeDecodeError
异常。
然而,它接受两个参数:
-
encoding - 字符串要编码到的编码类型
-
errors - 编码失败时的响应。有六种错误响应类型
- strict - 默认响应,在失败时引发 UnicodeDecodeError 异常
- ignore - 忽略结果中无法编码的 unicode
- replace - 将无法编码的 unicode 替换为问号 ?
- xmlcharrefreplace - 将无法编码的 unicode 替换为 XML 字符引用
- backslashreplace - 将无法编码的 unicode 替换为 \uNNNN 转义序列
- namereplace - 将无法编码的 unicode 替换为
\N{...}
转义序列
示例 1:编码为默认的 Utf-8 编码
# unicode 字符串
string = 'pythön!'
# 打印字符串
print('字符串是:', string)
# 默认编码为 utf-8
string_utf = string.encode()
# 打印结果
print('编码后的版本是:', string_utf)
输出
字符串是: pythön!
编码后的版本是: b'pyth\xc3\xb6n!'
示例 2:带有错误参数的编码
# unicode 字符串
string = 'pythön!'
# 打印字符串
print('字符串是:', string)
# 忽略错误
print('编码后的版本(忽略错误)是:', string.encode("ascii", "ignore"))
# 替换错误
print('编码后的版本(替换错误)是:', string.encode("ascii", "replace"))
输出
字符串是: pythön!
编码后的版本(忽略错误)是: b'pythn!'
编码后的版本(替换错误)是: b'pyth?n!'
注意: 也可以尝试使用不同的编码和错误参数。
字符串编码
自 Python 3.0 以来,字符串被存储为 Unicode,即字符串中的每个字符都由一个代码点表示。因此,每个字符串只是一系列 Unicode 代码点的序列。
为了有效存储这些字符串,代码点序列被转换成一组字节。这个过程称为 编码。
存在各种各样的编码,它们以不同方式处理字符串。常见的编码有 utf-8、ascii 等。
使用字符串的 encode()
方法,您可以将 unicode 字符串转换为 Python 支持的任何编码。默认情况下,Python 使用 utf-8 编码。