字符串方法0x01 -- 编码
字符串不仅支持所有通用序列操作,还实现了很多附件方法。
我会以『字符串方法』为标题,分几篇笔记逐一介绍这些方法。
我会在这仓库中持续更新笔记:https://github.com/orca-j35/python_notes
encode
🔨 str.encode(encoding="utf-8", errors="strict")
Return an encoded version of the string as a bytes object. Default encoding is 'utf-8'
. errors may be given to set a different error handling scheme. The default for errors is 'strict'
, meaning that encoding errors raise a UnicodeError
. Other possible values are 'ignore'
, 'replace'
, 'xmlcharrefreplace'
, 'backslashreplace'
and any other name registered via codecs.register_error()
, see section Error Handlers. For a list of possible encodings, see section Standard Encodings.
# 对字符串进行编码
field = '鲸'
assert field.encode() == b'\xe9\xb2\xb8'
assert field.encode('ascii', 'ignore') == b''
assert field.encode('ascii', 'replace') == b'?'
# 40120是'鲸'的码点值(10进制)
assert field.encode('ascii', 'xmlcharrefreplace') == b'鲸'
# u9cb8是'鲸'的码点值(16进制)
assert field.encode('ascii', 'backslashreplace') == b'\\u9cb8'
field.encode('ascii') # 抛出 UnicodeEncodeError 异常
Tips: 在 Python 文档中,"编码(encoding)"是指将 Unicode 字符串转换为字节序列的规则,也就是说"编码"包含了从"抽象字符序列"到"字节序列"的全部过程;反之,"解码"则包含了从"字节序列"到"抽象字符序列"的全部过程。