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类型其实是同一种类型。
到了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
>>> 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
相关文章推荐
- Webdriver for Python中文教程(更新中)
- python 中的命令补全脚本
- leetcode 日经贴,python code -Word Search II
- python中利用lxml模块解析xml文件报错XMLSyntaxError: Opening and ending tag mismatch
- 今天看项目和框架的一些小知识
- [Python学习] 模块三.基本字符串
- 耗子学Python了(1)___Python环境配置
- python 常用string函数
- python-装饰器的学习
- 运行一个python项目的步骤
- 人生苦短,喝点python性能鸡汤
- python的内置函数
- Python安装cairo、gtk等问题
- Python学习-第一天
- PYTHON-mysql fetchall和 fetchone之间的区别
- python中的exec()函数的作用
- python 基础教程
- 使用国内镜像源来加速python pypi包的安装
- 国内的pythoner强烈建议使用豆瓣的pypi源 zz
- Python之Window环境搭建