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

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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值