Python的__future__模块

Python提供了__future__模块,把下一个新版本的特性导入到当前版本,于是我们就可以在当前版本中测试一些新版本的特性。

为了适应Python 3.x的新的字符串的表示方法,在2.7版本的代码中,可以通过unicode_literals来使用Python 3.x的新的语法:

这个模块的作用就是把你当前模块所以的字符串(string literals)转为unicode。

对于导入unicode_literals将当前模块所以的字符串(string literals)转为unicode。当传递string类型时就会报错,因此需要将unicode转化为string类型。Python2.7运行时默认的编码环境ASCII。于是python就通过ASCII来把unicode转为string

方法一:设置运行时编码为utf-8

#coding:utf-8
from __future__ import unicode_literals
import sys
from datetime import datetime

reload(sys)
sys.setdefaultencoding('utf-8')
 

方法二:使用byte string

#coding:utf-8
from __future__ import unicode_literals
from datetime import datetime

now = datetime.now()
print now.strftime(b'%m月%d日 %H:%M')  # 指明为bytearray字符串

# 或者这样也行
t = bytearray('%m月 %d %H:%M', 'utf-8')
print now.strftime(str(t))

Python 2.7的代码中直接使用Python 3.x的除法,可以通过__future__模块的division实现:

在Python 2.x中,对于除法有两种情况,如果是整数相除,结果仍是整数,余数会被扔掉,这种除法叫“地板除”。要做精确除法,必须把其中一个数变成浮点数。而在Python 3.x中,所有的除法都是精确除法,地板除用//表示

>>> from __future__ import division
>>> print 10/3
3.33333333333
>>>


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值