【Python】Python2与Python3的不同
前言
Python作为一种连接各种语言的胶水语言,以其自身优势在系统开发、web开发、网络爬虫、数据挖掘、深度学习等多方面均有广泛使用,Python也有其特殊之处:Python2.x与Python3.x并不兼容。今天看到消息说Python基金会宣布在2020年元旦开始将不提供任何Python 2.x的支持,所以觉得有必要再重新整理一下Python这两个版本间的差异。
编码
Python3源码文件默认使用utf-8编码,因此,如下代码合法:
>>> 中国 = 'china'
>>> print(中国)
china
字符串与Unicode
Python2中,字符串默认是字节字符串,而在Python3中是Unicode字符串。Python3行为可以通过下面命令导入到Python2中。
from __future__ import unicode_literals
同时,字节字符串与文本字符串的名称不同。在Python2中,str类用于表示字节字符串,unicode类用于表示文本字符串。在Python3中,则变为bytes与str。这意味着名称为str的类在两个版本中都存在,但代表着不同意义。
Print函数
从Python2到Python3,Python改变了print的工作机制。在Python2中,print是一个特殊语句,如下所示:
print 'Hello World'
默认情况下,print会写到sys.stdout并在字符串结尾附加\n,然而,print可以通过使用特殊语法>>打印到其他地方,如下:
import sys
print >> sys.stderr,'Hello World!'
在Python3中,print成为一个函数,这个函数接受一个名为file的关键字参数,其默认值为sys.stdout,如下:
import sys
print('Hello World!',file=sys.stderr)
另外,新的print函数也更加灵活,可以通过使用end关键字参数来改变默认在字符串结尾附加的\n的行为。
Python3的print函数在Python2.x的__future__模块中可用,使用如下:
from __future__ import print_function
除法
在Python2中,除法(/)操作符用于两个整型数,和整除(//)一样都会返回int类型,为了避免无法整除的现象,只能使用小数点使得被除数为float型,如下:
>>> 4/2
2
>>> 5/2
2
>>> 5//2
2
>>> 5.0/2
2.5
而Python3则通过整数除法总是返回float型修复了这个行为,如果需要求整除,可以使用“//”,如下:
>>> 4/2
2.0
>>> 5/2
2.5
>>> 5//2
2
运算符的差异
在Python 3.x中,修正了“不相等”运算符,只能使用“!=”,而Python 2.x中,使用“<>”和“!=”都可以,如下:
# Python 2.x
>>> 0 <> 1
True
>>> 0 != 1
True
# Python 3.x
>>> 0 <> 1
SyntaxError: invalid syntax
>>> 0 != 1
True
模块名称改变
Python 2.x | Python 3.x |
---|---|
itertools.ifilter | filter |
itertools.map | map |
itertools.izip | zip |
ConfigParser | configparser |
raw_input | input |
xrange | range |
reduce | functools.reduce |
一些函数的使用差异
(1)输入函数raw_input和input
在Python 2.x中,需使用raw_input函数,而Python 3.x改为input函数,如下:
# Python 2.x
>>> raw_input("Please input the content: ")
Please input the content: roguesir
'roguesir'
# Python 3.x
>>> input("Please input the content: ")
Please input the content: roguesir
'roguesir'
(2)爬虫常用模块urllib2和urllib3
在Python 3.x中,舍弃了urllib2这个模块,这个差异主要是由于Python 3.x的编码方式改变引起的。
# Python 2.x
>>> import urllib2
>>> import urllib3
# Python 3.x
>>> import urllib2
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
import urllib2
ModuleNotFoundError: No module named 'urllib2'
>>> import urllib3
(3)异常捕获
在Python 2.x中,使用异常捕获函数如果不加”as”则会报错,而Python 3.x则没有限制,如下:
# Python 2.x
>>> try:
i == 1
except Exception as e:
print e
# Python 3.x
>>> try:
i == 1
except Exception as e:
print(e)
>>> try:
i == 1
except Exception:
print('Found an error!')
更新时间:2019-04-02
还没有评论,来说两句吧...