天天看點

Python 2與Python 3的差別

越來越多的庫要放棄Python 2了,我也開始轉向Python 3了。最近的項目開始用Python3寫了,也體會了一下2和3的差別。主要的一些差別在以下幾個方面:

  • print函數
  • 整數相除
  • Unicode
  • 異常處理
  • xrange
  • map函數
  • 不支援has_key

print函數

Python 2中print是語句(statement),Python 3中print則變成了函數。在Python 3中調用print需要加上括号,不加括号會報SyntaxError

Python 2

print "hello world"
           

輸出

hello world
           

Python 3

print("hello world")
           

輸出

hello world
           
print "hello world"
           

輸出

File "<stdin>", line 1
    print "hello world"
                      ^
SyntaxError: Missing parentheses in call to 'print'
           

整數相除

在Python 2中,3/2的結果是整數,在Python 3中,結果則是浮點數

Python 2

print '3 / 2 =', 3 / 2
print '3 / 2.0 =', 3 / 2.0
           

輸出

3 / 2 = 1
3 / 2.0 = 1.5
           

Python 3

print('3 / 2 =', 3 / 2)
print('3 / 2.0 =', 3 / 2.0)
           

輸出

3 / 2 = 1.5
3 / 2.0 = 1.5
           

Unicode

Python 2有兩種字元串類型:str和unicode,Python 3中的字元串預設就是Unicode,Python 3中的str相當于Python 2中的unicode。

在Python 2中,如果代碼中包含非英文字元,需要在代碼檔案的最開始聲明編碼,如下

# -*- coding: utf-8 -*-
           

在Python 3中,預設的字元串就是Unicode,就省去了這個麻煩,下面的代碼在Python 3可以正常地運作

a = "你好"
print(a)
           

異常處理

Python 2中捕獲異常一般用下面的文法

try:
    1/0 
except ZeroDivisionError, e:
    print str(e)
           

或者

try:
    1/0 
except ZeroDivisionError as e:
    print str(e)
           

Python 3中不再支援前一種文法,必須使用as關鍵字。

xrange

Python 2中有 range 和 xrange 兩個方法。其差別在于,range傳回一個list,在被調用的時候即傳回整個序列;xrange傳回一個iterator,在每次循環中生成序列的下一個數字。Python 3中不再支援 xrange 方法,Python 3中的 range 方法就相當于 Python 2中的 xrange 方法。

map函數

在Python 2中,map函數傳回list,而在Python 3中,map函數傳回iterator。

Python 2

map(lambda x: x+1, range(5))
           

輸出

[1, 2, 3, 4, 5]
           

Python 3

map(lambda x: x+1, range(5))
           

輸出

<map object at 0x7ff5b103d2b0>
           
list(map(lambda x: x+1, range(5)))
           

輸出

[1, 2, 3, 4, 5]
           

filter函數在Python 2和Python 3中也是同樣的差別。

不支援has_key

Python 3中的字典不再支援has_key方法

Python 2

person = {"age": 30, "name": "Xiao Wang"}
print "person has key \"age\": ", person.has_key("age")
print "person has key \"age\": ", "age" in person
           

輸出

person has key "age":  True
person has key "age":  True
           

Python 3

person = {"age": 30, "name": "Xiao Wang"}
print("person has key \"age\": ", "age" in person)
           

輸出

person has key "age":  True
           
print("person has key \"age\": ", person.has_key("age"))
           

輸出

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'has_key'
           

以上是最近整理的一些,後續會繼續更新,也歡迎大家補充。

本文已更新微信同名公衆号【Python與資料分析】,歡迎關注~