Tutorial Study Image

Python encode()

Python 中的 encode() 函数有助于将给定字符串转换为编码格式。如果未指定编码,则默认使用 UTF-8。


string.encode(encoding='UTF-8',errors='strict') #where encodings being utf-8, ascii, etc
 

encode() 参数

encode() 函数接受两个可选参数。其中参数 errors 可以是以下六种类型之一。

  • strict - 失败时的默认响应。
  • ignore - 忽略不可编码的 Unicode
  • replace - 将不可编码的 Unicode 替换为问号 (?)
  • xmlcharrefreplace - 插入 XML 字符引用代替不可编码的 Unicode
  • backslashreplace - 插入 \uNNNN 转义序列代替不可编码的 Unicode
  • namereplace - 插入 \N{...} 转义序列代替不可编码的 Unicode
参数 描述 必需/可选
encoding(编码) 要编码的字符串的编码类型 可选
errors(错误处理) 编码失败时的响应 可选

encode() 返回值

默认情况下,函数使用 utf-8 编码,如果发生任何失败,它会引发 UnicodeDecodeError 异常。

输入 返回值
字符串 编码字符串

Python 中 encode() 方法的示例

示例 1:如何将字符串编码为默认的 Utf-8 编码?


# 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!'

示例 2:编码如何与 error 参数一起使用?


# 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!'