Python 字符串 encode()

encode() 方法返回给定字符串的编码版本。

示例

title = 'Python Programming'

# change encoding to utf-8 print(title.encode())
# Output: b'Python Programming'

字符串 encode() 的语法

encode() 方法的语法是

string.encode(encoding='UTF-8',errors='strict')

字符串 encode() 参数

默认情况下,encode() 方法不需要任何参数。

它返回字符串的 utf-8 编码版本。如果失败,它会引发 UnicodeDecodeError 异常

但是,它接受两个参数

  • encoding - 字符串要编码的编码类型
  • errors - 编码失败时的响应。有六种错误响应类型
    • strict - 默认响应,在失败时引发 UnicodeDecodeError 异常
    • ignore - 忽略结果中无法编码的 Unicode
    • replace - 将无法编码的 Unicode 替换为问号 ?
    • xmlcharrefreplace - 插入 XML 字符引用而不是无法编码的 Unicode
    • backslashreplace - 插入 \uNNNN 转义序列而不是无法编码的 Unicode
    • namereplace - 插入 \N{...} 转义序列而不是无法编码的 Unicode

示例 1:编码为默认 Utf-8 编码

# unicode string
string = 'pythön!'

# print string
print('The string is:', string)

# default encoding to utf-8
string_utf = string.encode()
# print result print('The encoded version is:', string_utf)

输出

The string is: pythön!
The encoded version is: b'pyth\xc3\xb6n!'

示例 2:带错误参数的编码

# unicode string
string = 'pythön!'

# print string
print('The string is:', string)

# ignore error
print('The encoded version (with ignore) is:', string.encode("ascii", "ignore"))
# replace error
print('The encoded version (with replace) is:', string.encode("ascii", "replace"))

输出

The string is: pythön!
The encoded version (with ignore) is: b'pythn!'
The encoded version (with replace) is: b'pyth?n!'

注意: 也可以尝试不同的编码和错误参数。


字符串编码

自 Python 3.0 起,字符串存储为 Unicode,即字符串中的每个字符都由一个代码点表示。因此,每个字符串都只是一系列 Unicode 代码点。

为了高效存储这些字符串,代码点序列被转换为一组字节。这个过程称为编码

存在各种编码,它们对字符串的处理方式不同。流行的编码有 utf-8ascii 等。

使用字符串 encode() 方法,您可以将 Unicode 字符串转换为 Python 支持的任何编码。默认情况下,Python 使用 utf-8 编码。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战