环境:windows简体中文 + Python2.7,当前环境 str 默认显示编码为 gbk(Linux 环境中 Python2.7 默认显示编码为 utf8)python
>>> a = '你' >>> a '\xc4\xe3'
# 对应 gbk 编码
>>> a.encode() UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 0: ordinal not in range(128) # 当 a.encode() 执行时,python 解释器发现 a 的编码格式为 GBK ,可是只有 unicode 编码才能进行 encode,因此系统帮咱们执行了 a.decode().encode() # 在 python2 中系统默认的 encoding 编码为 ascii,因此至关于 a.decode('ascii').encode('ascii') # 查看系统默认 encoding 编码 >>> import sys >>> sys.getdefaultencoding() 'ascii' # 因 ascii 编码中不支持中文字符,因此在执行到 decode时就出现了报错 UnicodeDecodeError # 能够将 a 解码为 unicode,再编码为 utf8格式 >>> a.decode('gbk') u'\u4f60' >>> a.decode('gbk').encode('utf8') '\xe4\xbd\xa0' #在 pyhton2 中定义 unicode 编码的字符串 >>> b u'\u6211' >>> b.encode() UnicodeEncodeError: 'ascii' codec can't encode character u'\u6211' in position 0: ordinal not in range(128) # 在 python2 中系统默认的 encoding 编码为 ascii,因此至关于执行了 a.encode('ascii') # ascii 编码中不支持中文字符,因此出现了UnicodeEncodeError # 能够把字符串b编码为 uft8 或者 gbk 格式,由于这两种编码都支持中文字符 >>> b.encode('utf8') '\xe6\x88\x91' >>> b.encode('gbk') '\xce\xd2'
在 Python3 中字符串统一使用 unicode编码,而且系统默认 encoding 为 utf8windows
>>> import sys >>> print(sys.getdefaultencoding()) utf-8
>>> a = "你好" >>> a.encode() b'\xe4\xbd\xa0\xe5\xa5\xbd'
>>> a.encode().decode() '你好' >>> a.encode('gbk').decode('gbk') '你好'