Python2默认字符串类型str,使用ascii编码。
>>> type('123')
<type 'str'>
>>> '123'.decode('ascii')
u'123'
而对于包含中文的字符串,使用gb2312编码,不过仍然是str类型。
>>> type('中文')
<type 'str'>
>>> '中文'.decode('gb2312')
u'\u4e2d\u6587'
当然,如果是明确以u修饰的字符串,那就是unicode类型了。
>>> type(u'123')
<type 'unicode'>
>>> type(u'中文')
<type 'unicode'>
另外,在Python2中,str类型和bytes类型其实是同一种类型。
>>> id(str)
505580560
>>> id(bytes)
505580560
>>> str is bytes
True
>>> bytes is str
True
>>> type('123')
<class 'str'>
>>> '123'.encode('ascii')
b'123'
>>> type('中文')
<class 'str'>
>>> '中文'.encode('utf-8')
b'\xe4\xb8\xad\xe6\x96\x87'
因此,在Python3中不再有单独的unicode类型。
>>> unicode
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
unicode
NameError: name 'unicode' is not defined