阿里山QQ

导航

使用__future__实现从python2.7到python3.x的过渡

参考链接:http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386820023084e5263fe54fde4e4e8616597058cc4ba1000

在python2.7到3.x有一些不兼容的改动,如果直接升级python的版本,会导致一些旧版本的python代码不可执行;为了解决这一问题,python社区开发了__future__模块;

 

1.字符串兼容

在python2.7中,任意创建的字符串对象,比如a='str1',默认都表示字符串类型,如果需要将其转换为unicode码,就需要在字符串前面加上u,即a=u'str1';

在python3.x中,任意创建的字符串,默认都是unicode码的,

from __future__ import unicode_literals
print '\'xxx\' is unicode?',isinstance('xxx',unicode)
print 'u\'xxx\' is unicode?',isinstance(u'xxx',unicode)
print '\'xxx\' is str?',isinstance('xxx',str)
print 'b\'xxx\' is str?',isinstance(b'xxx',str)


结果:
'xxx' is unicode? True
u'xxx' is unicode? True
'xxx' is str? False
b'xxx' is str? True

 

2、除法兼容

python2的地板除法,默认会只保留整数部分,如果要保留小数部分,需要

 

posted on 2017-03-23 15:38  阿里山QQ  阅读(178)  评论(0编辑  收藏  举报