Python2 Python3 str类型比较
Python2
type("str") #<type 'str'> type(b"str") #<type 'str'> type(u"str") #<type 'unicode'>
Python3
type("str") #<type 'str'> type(b"str") #<class 'bytes'> type(u"str") #<type 'str'>
#!/usr/bin/python
#-*- coding:UTF-8 -*-
s='代码' #python2 会自动将字符串转换为合适编码的字节字符串,自动转换为UTF-8编码的字节字符串 '\xe4\xbb\xa3\xe7\xa0\x81'
u=u'代码' #显式指定字符串类型为unicode类型, 此类型字符串没有编码,保存的是字符在unicode字符集中的代码点(序号) u'\u4ee3\u7801'
print len(s) #6
print len(u) #2
print repr(s) #'\xe4\xbb\xa3\xe7\xa0\x81'
print repr(u) #u'\u4ee3\u7801'
#print s.encode('utf-8') #UnicodeDecodeError: 'ascii' codec can't decode
#python2 已经自动将其转化为utf-8类型编码,因此再次编码会报错
print repr(s.decode('utf-8')) #u'\u4ee3\u7801'
#python2 可以正常解码,返回的字符串类是无编码的unicode类型
print repr(u.encode('utf-8')) #'\xe4\xbb\xa3\xe7\xa0\x81'
#print repr(u.decode('utf-8')) #UnicodeEncodeError: 'ascii' codec can't encode characters
b=b'代码' #已被python2转换为utf-8编码,因此已为字节字符串
print len(b) #6
print repr(b) #'\xe4\xbb\xa3\xe7\xa0\x81
print repr(b.decode('utf-8')) #u'\u4ee3\u7801'
#print repr(b.encode('utf-8')) #UnicodeDecodeError: 'ascii' codec can't decode byte
严格意义上说,str其实是字节串(Python2中,字符串字面量对应于8位字符或者面向字节的数据),它是unicode经过编码后的字节组成的序列;对UTF-8编码的str'代码'使用len()函数时,结果是6,因为实际上,UTF-8编码的'代码' == '\xe4\xbb\xa3\xe7\xa0\x81';unicode才是真正意义上的字符串,对字节串str使用正确的字符编码进行解码后获得,并且len(u'代码') == 2
Python3中的编码
#!/usr/local/bin/python3 #-*- coding: UTF-8 -*- s='代码' print(repr(s)) #代码 print(s.encode('utf-8')) #b'\xe4\xbb\xa3\xe7\xa0\x81' type(s) # <class 'str'> type(s.encode('utf-8')) #<class 'bytes'> type(b'str') #<class 'bytes'> print(s.decode('utf-8')) #AttributeError: 'str' object has no attribute 'decode'
Python3中,所有字符串已是Unicode编码,只能encode为某一个编码类型的字节字符串bytes,而不能decode
参考:
http://www.cnblogs.com/huxi/archive/2010/12/05/1897271.html Python字符编码详解
http://www.cnblogs.com/geekard/archive/2012/10/04/python-string-endec.html Python的字符编码
http://book.douban.com/subject/5401851/ 《Python参考手册》(第四版)2.4节
<script type="text/javascript">
</script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>