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
>>>