1. print 函数

  • Python 2print 是语句(statement);
  • Python 3print 则变成了函数;

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 有两种字符串类型:strunicode
  • Python 3 中的字符串默认就是 UnicodePython 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 中有 rangexrange 两个方法。其区别在于,

  • range 返回一个 list,在被调用的时候即返回整个序列;
  • xrange 返回一个 iterator,在每次循环中生成序列的下一个数字;

Python 3 中不再支持 xrange 方法,Python 3 中的 range 方法就相当于 Python 2 中的 xrange 方法。

6.2 高阶函数

  • Python 2zip(), map()filter() 直接返回列表;
  • Python 3zip(), 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. 语法方面

  • 关键词加入 aswith,还有 True, False, None
  • 加入 nonlocal 语句。使用 noclocal x 可以直接指派外围(非全局)变量;
  • 同样的还有 exec 语句,已经改为 exec() 函数 ;
  • 输入函数改变了,删除了 raw_input,用 input 代替;
  • 扩展的可迭代解包。在 Python 3 里,a, b, *rest = seq*rest, a = seq 都是合法的,只要求两点:restlist
  • 迭代器的 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 2TrueFalse 是两个全局变量(名字),在数值上分别对应 10
  • Python 3 修正了这个缺陷,TrueFalse 变为两个关键字,永远指向两个固定的对象,不允许再被重新赋值;

12. 待补充