码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-03-23 15:57:59      阅读:447      评论:0      收藏:0      [点我收藏+]

标签:nbsp   als   模块   小数   转换   2.7   int   保留   str   

参考链接: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的过渡

标签:nbsp   als   模块   小数   转换   2.7   int   保留   str   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!