Python2/3的中、英文字符编码与解码输出: UnicodeDecodeError: 'ascii' codec can't decode/encode Python3的字符编码与解码输出 Python2的字符编码与解码输出 总结

Python中文虐我千百遍,我待Python如初恋。本文主要介绍在Python2/3交互模式下,通过对中文、英文的处理输出,理解Python的字符编码与解码问题(以点破面)。

前言:字符串的编码一开始是 ascii,只支持英文,由于多种语言的存在,出现万国码 unicode,但 unicode 不兼容 ascii,而且对存储空间造成浪费,所以出现 utf-8 编码,一种针对 unicode 的可变长度字符编码。

  1 >>> hi = b'hello, world'
  2 >>> hi
  3 b'hello, world'
  4 >>> print(hi)
  5 b'hello, world'
  6 >>> hi.decode('utf-8')
  7 'hello, world'
  1 >>> hey = '你好'
  2 >>> hey
  3 '你好'
  4 >>> print(hey)
  5 你好
  6 >>> unihey = hey.encode('unicode_escape')
  7 >>> unihey
  8 b'\u4f60\u597d'
  9 >>> print(unihey)
 10 b'\u4f60\u597d'
 11 >>> unihey.decode('unicode_escape')
 12 '你好'
 13 >>> 'u4f60u597d'
 14 '你好'

在 Python3 *有两种字符序列。一种是 str 序列,默认对字符串编码;一种是 bytes 序列,操作二进制数据流,如代码段一中的 hi,通过在字符串前的 b,即表示 bytes 。这两种序列可通过 decode 和 encode 相互转换,如下图:

Python2/3的中、英文字符编码与解码输出: UnicodeDecodeError: 'ascii' codec can't decode/encode
Python3的字符编码与解码输出
Python2的字符编码与解码输出
总结

在代码段一中,通过对 bytes 以 utf-8 的格式解码,得到 str。除此之外,还可通过 unicode_escape、gbk 等格式解码;

在代码段二中,通过对 str 的中文 hey 以 unicode_escape 的格式编码,得到 bytes 。用什么格式编码就用什么解码,即可得到原字符。

由于 Python3 对中文的支持友好,将 unihey 中的转义符 去掉,在交互模式下可直接显示中文。

在网络传输中,如 urllib、request 等获取数据的库,通常返回 bytes 序列,这时可通过 decode 指定相应的格式经行解码,获取中文字符。

Python2的字符编码与解码输出

  1 >>> hi = u'hello, world'
  2 >>> hi
  3 u'hello, world'
  4 >>> print hi
  5 hello, world
  6 >>> hi.encode('utf-8')
  7 'hello, world'
  8 >>> hi.encode('unicode_escape')
  9 'hello, world'
  1 >>> hey = '你好'
  2 >>> hey
  3 'xc4xe3xbaxc3'
  4 >>> print hey
  5 你好
  6 >>> uhey = u'你好'
  7 >>> uhey
  8 u'u4f60u597d'
  9 >>> print uhey
 10 你好
 11 >>> ghey = uhey.encode('gbk')
 12 >>> ghey
 13 'xc4xe3xbaxc3'
 14 >>> print ghey
 15 你好
 16 >>> hey.decode('gbk')
 17 u'u4f60u597d'
 18 >>> print hey.decode('gbk')
 19 你好
 20 >>> 'u4f60u597d'
 21 '\u4f60\u597d'

在 Python2 中也有两种字符序列。一种是 unicode 序列,如代码段一中的 hi,通过在字符串前的 u,即表示 unicode,相当于 Python3 中的 str;一种是 str 序列,相当于 Python3 中的 bytes 。这两种序列可通过 decode 和 encode 相互转换,如下图:

Python2/3的中、英文字符编码与解码输出: UnicodeDecodeError: 'ascii' codec can't decode/encode
Python3的字符编码与解码输出
Python2的字符编码与解码输出
总结

在代码段一中,通过对 unicode 以 utf-8、unicode_escape 的格式编码,得到 str;

在代码段二中,通过对 str 的中文 hey 以 gbk 的格式解码,得到 unicode;对 unicode 的中文 uhey 以 gbk 的格式编码,得到 str 。

在 Python 的交互模式下,直接输出是 Python 所理解的代码中的状态,而 print 输出的是给用户看到。

从代码段二的20行、21行可以看出,Python2 对中文的支持没有 Python3 友好。除此之外,当列表中有中文时,Python2 必须遍历列表,才能在交互模式下看到中文,而 Python3 直接打印列表即可。

总结

上述表述可能不到位,欢迎交流讨论!同时我们可以通过 Anaconda 切换不同的 Python 环境,去尝试上述小栗子,随便编码解码,玩坏了算我输~( ̄▽ ̄)~