1. print 函数
-
Python 2
中print
是语句(statement); -
Python 3
中print
则变成了函数;
在 Python 3
中调用 print
需要加上括号,不加括号会报 SyntaxError
。
-
Python 2
中使用逗号,
表示不换行; -
Python 3
中使用print ("hi",end="")
使用end=""
表示不换行;
2. 整数相除
-
Python 2
中,3/2 的结果是整数; -
Python 3
中,结果则是浮点数;
3. 编码方式
-
Python 2
中的默认编码是ASSCII
,至于是为什么会使用asscii
作为默认编码,原因在于Python 2
出来的时候还没出现Unicode
。 -
Python 3
默认采用了UTF-8
作为默认编码,因此你不再需要在文件顶部写# coding=utf-8
了。
4. 字符串
-
Python 2
有两种字符串类型:str
和unicode
; -
Python 3
中的字符串默认就是Unicode
,Python 3
中的str
相当于Python 2
中的unicode
;
5. 异常处理
Python 2
中捕获异常一般用下面的语法:
try:
1/0
except ZeroDivisionError, e:
print str(e)
或者
try:
1/0
except ZeroDivisionError as e:
print str(e)
Python 3
中不再支持前一种语法,必须使用 as
关键字。
6. 内置函数
6.1 xrange
Python 2
中有 range
和 xrange
两个方法。其区别在于,
-
range
返回一个list
,在被调用的时候即返回整个序列; -
xrange
返回一个iterator
,在每次循环中生成序列的下一个数字;
Python 3
中不再支持 xrange
方法,Python 3
中的 range
方法就相当于 Python 2
中的 xrange
方法。
6.2 高阶函数
-
Python 2
中zip()
,map()
和filter()
直接返回列表; -
Python 3
中zip()
,map()
和filter()
直接返回迭代器,如果要变列表,必须要加list
;
迭代器和列表的区别,请参考
6.3 字典
Python 3
中字典里面 dict.keys()
, dict.items()
和 dict.values()
方法返回迭代器,去掉了 Python 2
里面的 iterkeys()
,去掉的 dict.has_key()
,Python 3
中用 in
替代它。
7. 赋值变量
Python 2
中
a,b,*res=[1,2,3,4]
这样写是会报错的,但是 Python 3
里面写就合法。
8. 类的继承
Python 2
里面子类继承父类经常要写 super
这个函数,就是子类初始的话要记得初始化父类,这时 super()
里面要填一些参数。
class Parent(object):
def __init__(self):
self.a = 100
class Child(Parent):
def __init__(self):
super(Child, self).__init__()
c = Child()
print c.a
Python 3
里面直接简化了这个过程,省掉 super()
里面的参数,更简洁更 Pythonic
。
class Parent(object):
def __init__(self):
self.a = 100
class Child(Parent):
def __init__(self):
super().__init__()
c = Child()
print c.a
9. 语法方面
- 关键词加入
as
和with
,还有True
,False
,None
; - 加入
nonlocal
语句。使用noclocal x
可以直接指派外围(非全局)变量; - 同样的还有
exec
语句,已经改为exec()
函数 ; - 输入函数改变了,删除了
raw_input
,用input
代替; - 扩展的可迭代解包。在
Python 3
里,a, b, *rest = seq
和*rest, a = seq
都是合法的,只要求两点:rest
是list
; - 迭代器的
next()
方法改名为__next__()
,并增加内置函数next()
,用以调用迭代器的__next__()
方法 ;
10. 数据类型
新增了 bytes
类型,对应于 Python 2
版本的八位串,定义一个 bytes
字面量的方法如下:
>>> b = b'china'
>>> type(b)
<type 'bytes'>
str
对象和 bytes
对象可以使用 .encode() (str -> bytes)
or .decode() (bytes -> str)
方法相互转化。
>>> s = b.decode()
>>> s
'china'
>>> b1 = s.encode()
>>> b1
b'china'
11. True 和 False
-
Python 2
中True
和False
是两个全局变量(名字),在数值上分别对应1
和0
; -
Python 3
修正了这个缺陷,True
和False
变为两个关键字,永远指向两个固定的对象,不允许再被重新赋值;
12. 待补充