Python中文虐我千百遍,我待Python如初恋。本文主要介绍在Python2/3交互模式下,通过对中文、英文的处理输出,理解Python的字符编码与解码问题(以点破面)。
前言:字符串的编码一开始是 ascii,只支持英文,由于多种语言的存在,出现万国码 unicode,但 unicode 不兼容 ascii,而且对存储空间造成浪费,所以出现 utf-8 编码,一种针对 unicode 的可变长度字符编码。
Python3的字符编码与解码输出
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'