python2.+进化至python3.+ 语法变动差异

一时失言乱红尘 2022-12-05 09:51 190阅读 0赞

转自http://www.mamicode.com/info-detail-1654914.html

1、输出

python2.+  输出:  print “”

python3.+  输出:  print (“”)

2、打开文件

python2.+  打开文件:  file()或open()

python3.+  打开文件:  open()

3、thread模块

python2.+  导入thread模块:  import thread

线程运行方法: thread.start_new_thread()

python3.+  导入thread模块:  import _thread

线程运行方法: _thread.start_new_thread()

4、range和xrange

python2.+中 range(0,3)获得一个list,在python3.+中必须显示调用list(range(0,3))

python2.+中 xrange(0,4),在python3.+中改名为range(0,4)

5、python2.+中 raw_input,在python3.+中改名为input

6、python2.+中 long,在python3.+中改名为int

7、python2.+中 except Exception, e 在python3.+中改为except (Exception) as e

8、python3.+中zip()、map()和filter()都返回迭代器。

而python2.+中的apply()、 callable()、coerce()、 execfile()、reduce()和reload ()函数都被去除了

python3.+可以使用hasattr()来替换callable(),hasattr()的语法如:hasattr(string, ‘name‘)

python3.+可以使用self.func(*self.args)来替换apply(self.func,self.args)

9、python2.+中的<>,在python3.+中全部改用!=

10、python3.+关键词加入as 和with,还有True,False,None

11、python3.+整型除法返回浮点数,1/2结果为0.5,要得到整型结果,使用//

12、python3.+加入nonlocal语句。使用noclocal x可以直接指派外围(非全局)变量

13、输入函数raw_input

python2.+输入函数raw_input,python3.+中用input代替

14、python3.+中bytes对象不能hash,也不支持 b.lower()、b.strip()和b.split()方法,但对于后两者可以使用 b.strip(b’
\n\t\r \f’)和b.split(b’ ‘)来达到相同目的

发表评论

表情:
评论列表 (有 0 条评论,190人围观)

还没有评论,来说两句吧...

相关阅读