python_使用__future__
2016-05-01 19:34
423 查看
Python的新版本会引入新的功能,但是,实际上这些功能在上一个老版本中就已经存在了。要“试用”某一新的特性,就可以通过导入__future__模块的某些功能来实现。
例如,Python 2.7的整数除法运算结果仍是整数:
>>> 10 / 3
3
但是,Python 3.x已经改进了整数的除法运算,“/”除将得到浮点数,“//”除才仍是整数:
>>> 10 / 3
3.3333333333333335
>>> 10 // 3
3
要在Python 2.7中引入3.x的除法规则,导入__future__的division:
>>> from __future__ import division
>>> print 10 / 3
3.3333333333333335
当新版本的一个特性与旧版本不兼容时,该特性将会在旧版本中添加到__future__中,以便旧的代码能在旧版本中测试新特性。
在Python 3.x中,字符串统一为unicode,不需要加前缀 u,而以字节存储的str则必须加前缀 b。请利用__future__的unicode_literals在Python 2.7中编写unicode字符串。
使用from __future__ import unicode_literals将把Python 3.x的unicode规则带入Python 2.7中。
参考代码:
from __future__ import unicode_literals
s = 'am I an unicode?'
print isinstance(s, unicode)
例如,Python 2.7的整数除法运算结果仍是整数:
>>> 10 / 3
3
但是,Python 3.x已经改进了整数的除法运算,“/”除将得到浮点数,“//”除才仍是整数:
>>> 10 / 3
3.3333333333333335
>>> 10 // 3
3
要在Python 2.7中引入3.x的除法规则,导入__future__的division:
>>> from __future__ import division
>>> print 10 / 3
3.3333333333333335
当新版本的一个特性与旧版本不兼容时,该特性将会在旧版本中添加到__future__中,以便旧的代码能在旧版本中测试新特性。
在Python 3.x中,字符串统一为unicode,不需要加前缀 u,而以字节存储的str则必须加前缀 b。请利用__future__的unicode_literals在Python 2.7中编写unicode字符串。
使用from __future__ import unicode_literals将把Python 3.x的unicode规则带入Python 2.7中。
参考代码:
from __future__ import unicode_literals
s = 'am I an unicode?'
print isinstance(s, unicode)
相关文章推荐
- Python3下sqlalchemy对mysql数据库的配置
- Windows 7(64-bit)下安装和配置Theano 并实现完美 GPU (GTX 970)加速
- Python模块--Python学习笔记三
- read the python code and predict the results --- from <Learn Python The Hard Way>
- Python 装饰器
- 关于Win下“ImportError: No module named _curses”的解决方案
- 如何用Notepad++运行Python脚本
- numpy的100个练习(一)
- python 数据类型基础
- python 文档字符串 关键字参数 默认参数 传递函数和lambda函数
- Python-sorted与sort,以及模拟内置函数sorted()
- FTP python编程
- Pandas入门(二)——DataFrame结构及常用操作
- (python解析js)selenium结合phantomjs抓取js生成的页面
- python脚本一键抓考试资料网答案
- Quick Leaner学Python
- Pandas模块入门(一)——Series结构介绍
- python基础(二)
- python插入内容到指定文件的位置
- 【LeetCode】Reverse Linked List 解题报告(Python & java)