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

创新互联从2013年成立,是专业互联网技术服务公司,拥有项目成都做网站、网站制作网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元唐山做网站,已为上家服务,为唐山各地企业和个人服务,联系电话:028-86922220
**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'pyth\xc3\xb6n!'示例 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!' 本文名称:创新互联Python教程:Python encode()
地址分享:http://www.jxjierui.cn/article/djeepoh.html


咨询
建站咨询
