首页 > 编程语言 > 详细

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

时间:2017-03-23 15:58:00      阅读:264      评论:0      收藏:0      [点我收藏+]

参考链接: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的地板除法,默认会只保留整数部分,如果要保留小数部分,需要

 

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

原文:http://www.cnblogs.com/cqq-20151202/p/6603596.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!