您的位置:首页 > 编程语言 > Python开发

python2/3差异之——字符串差异

2015-08-10 19:16 681 查看
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


到了Python3,默认字符串类型str是以unicode编码,所以所有语言的字符都可以直接用str类型表示。
>>> 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: