Python encode()

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

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

编码()参数:

encode()函数接受两个可选参数。这里的参数错误有六种类型。

  • 失败时的严格默认响应。
  • 忽略-忽略不可编码的 unicode
  • replace -将不可编码的 unicode 替换为问号(?)
  • XML arreffreplace-它不是不可编码的 unicode,而是插入 XML 字符引用
  • backslashreplace 插入 uNNNN 转义序列,而不是不可编码的 unicode
  • 名称替换-它插入了一个N{而不是不可编码的 unicode...}转义序列
参数 描述 必需/可选
编码 字符串必须编码到的编码类型 可选择的
错误 编码失败时的响应 可选择的

编码()返回值

默认情况下,函数使用 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'pythxc3xb6n!' 

示例 2:编码如何处理错误参数?

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

你可能感兴趣的