Python3 字符编解码
什么是字符编解码
- 编码:根据编码格式将
人类认识的字符
转为字节流
。 - 解码:根据编码格式将
字节流
转为人类认识的字符
。
Python3 中的字符编码
-
utf-8
为Python3
的默认编码格式,可通过以下语句查看:import sys print(sys.getdefaultencoding())
-
Python中使用方法
encode
来进行字符串的编码:foo_str = '我丢你' # encode 方法将人类认识的字符串 我丢你 转换成了字节流 foo_bytes = foo_str.encode('utf-8') # 输出为 b'\xe6\x88\x91\xe4\xb8\xa2\xe4\xbd\xa0' <class 'bytes'> print(foo_bytes, type(foo_bytes))# 方法 ord 可以获得字符的 unicode 编码, print(ord('我')) # 29228 # 方法 chr 可以将 unicode 编码转为字符 print(chr(25105)) # 我
Python3 中的字符解码
-
Python中使用方法
decode
来进行字节流的解码:foo_bytes = b'\xe6\x88\x91\xe4\xb8\xa2\xe4\xbd\xa0' # decode 方法将字节流转换成了人类认识的字符串 我丢你 print(foo_bytes.decode('utf-8'))
乱码
-
如果编码和解码格式不一致,就会出现乱码问题,例如:
foo_str = '我丢你' # 使用 utf-8 进行编码 foo_bytes = foo_str.encode('utf-8') # 输出为 b'\xe6\x88\x91\xe4\xb8\xa2\xe4\xbd\xa0' <class 'bytes'> print(foo_bytes, type(foo_bytes))# 使用 gbk 进行解码,会出现以下错误: # 'gbk' codec can't decode byte 0xa0 in position 8: incomplete multibyte sequence print(foo_bytes.decode('gbk'))