Loading

Python的字符串编码

本文用实验详细地演示了Python2和Python3在字符串编码上的区别。

在Python2中,字符串字面量对应于8位的字符或面向字节编码的字节字面量。这些字符串的一个重要限制是它们无法完全地支持国际字符集和Unicode编码。为了解决这种限制,Python2对Unicode数据使用了单独的字符串类型。要输入Unicode字符串字面量,要在第一个引号前加上前最'u'。

 

Python2中还有一种称为字节字面量的字符串类型,它是指一个已经编码的字符串字面量,在Python2中字节字面量和普通字符串没有差别,因为在Python2中普通字符串实际上就是已经编码(非Unicode)的字节字符串。

 

在Python3中,不必加入这个前缀字符,否则是语法错误,这是因为所有的字符串默认已经是Unicode编码了。如果使用-U选项运行解释器,Python2会模拟这种行为(即所有字符串字面量将被作为Unicode字符对待,u前缀可以省略)。在Python3中,字节字面量变成了与普通字符串不同的类型。

 

~/download/firefox $ python2
Python 2.7.2 (default, Jun 29 2011, 11:17:09) 
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>>> '张俊' #python2 会自动将字符串转换为合适编码的字节字符串
'\xe5\xbc\xa0\xe4\xbf\x8a' #自动转换为utf-8编码的字节字符串

 

>>> u'张俊' #显式指定字符串类型为unicode类型, 此类型字符串没有编码,保存的是字符在unicode字符集中的代码点(序号)
u'\u5f20\u4fca'

 

>>> '张俊'.encode('utf-8')  #python2 已经自动将其转化为utf-8类型编码,因此再次编码(python2会将该字符串当作用ascii或unicode编码过)会出现错误。
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128)


>>> '张俊'.decode('utf-8')  #python2 可以正常解码,返回的字符串类是无编码的unicode类型
u'\u5f20\u4fca'


>>> b'张俊'   # ‘张俊' 已被python2转换为utf-8编码,因此已为字节字符串
'\xe5\xbc\xa0\xe4\xbf\x8a'


>>> print '张俊'
张俊


>>> print u'张俊'
张俊


>>> print b'张俊'
张俊
>>> 

 

 

~/download/firefox $ python3
Python 3.2.2 (default, Sep 5 2011, 04:33:58) 
[GCC 4.6.1 20110819 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.


>>> '张俊' #python3的字符串默认为unicode格式(无编码)
'张俊'


>>> u'张俊' #由于默认为unicode格式,因此字符串不用像python2一样显式地指出其类型,否则是语法错误。
File "<stdin>", line 1
u'张俊'
^
SyntaxError: invalid syntax


>>> type('张俊') #python3中文本字符串和字节字符串是严格区分的,默认为unicode格式的文本字符串
<class 'str'>


>>> '张俊'.decode('utf-8') #因为默认的文本字符串为unicode格式,因此文本字符串没有decode方法
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'decode'


>>> '张俊'.encode('utf-8') #将文本字符串编码,转换为已编码的字节字符串类型
b'\xe5\xbc\xa0\xe4\xbf\x8a'


>>> type('张俊'.encode('utf-8'))
<class 'bytes'>


>>> print ('张俊'.encode('utf-8')) #对于已编码的字节字符串,文本字符串的许多特性和方法已经不能使用。
b'\xe5\xbc\xa0\xe4\xbf\x8a'


>>>print ('张俊'.encode('utf-8'))
b'\xe5\xbc\xa0\xe4\xbf\x8a'

 

>>> print ('张俊'.encode('utf-8').decode('utf-8'))  #必须将字节字符串解码后才能打印出来
张俊

posted @ 2018-02-23 15:50  RainDavi  阅读(220)  评论(0编辑  收藏  举报