標籤:同名 5.5 ioerror 本質 error bytes unicode span 必須
核心類差異
Python3對Unicode字元的原生支援
Python2中使用 ASCII 碼作為預設編碼方式導致string有兩種類型str和unicode,Python3隻支援unicode的string。python2和python3位元組和字元對應關係為:
- 編碼&字串
字串:
py2:
unicode v = u"root" 本質上用unicode儲存(萬國碼)
(str/bytes) v = "root" 本質用位元組儲存
py3:
str v = "root" 本質上用unicode儲存(萬國碼)
bytes v = b"root" 本質上用位元組儲存
編碼:
py2:
- ascii
檔案頭可以修改:#-*- encoding:utf-8 -*-
py3:
- utf-8
檔案頭可以修改:#-*- encoding:utf-8 -*-
Python3採用的是絕對路徑的方式進行import。
Python2中相對路徑的import會導致標準庫匯入變得困難(想象一下,同一目錄下有file.py,如何同時匯入這個檔案和標準庫file)。Python3中這一點將被修改,如果還需要匯入同一目錄的檔案必須使用絕對路徑,否則只能使用相關匯入的方式來進行匯入。
Python2中存在老式類和新式類的區別,Python3統一採用新式類。新式類聲明要求繼承object,必須用新式類應用多重繼承。
Python3使用更加嚴格的縮排。Python2的縮排機制中,1個tab和8個space是等價的,所以在縮排中可以同時允許tab和space在代碼中共存。這種等價機制會導致部分IDE使用存在問題。Python3中1個tab只能找另外一個tab替代,因此tab和space共存會導致報錯:TabError: inconsistent use of tabs and spaces in indentation.
廢棄類差異
print語句被python3廢棄,統一使用print函數
exec語句被python3廢棄,統一使用exec函數
execfile語句被Python3廢棄,推薦使用exec(open("./filename").read())
不相等操作符"<>"被Python3廢棄,統一使用"!="
long整數類型被Python3廢棄,統一使用int
xrange函數被Python3廢棄,統一使用range,Python3中range的機制也進行修改並提高了大資料集產生效率
Python3中這些方法再不再返回list對象:dictionary關聯的keys()、values()、items(),zip(),map(),filter(),但是可以通過list強行轉換:
mydict={"a":1,"b":2,"c":3}mydict.keys() #<built-in method keys of dict object at 0x000000000040B4C8>list(mydict.keys()) #[‘a‘, ‘c‘, ‘b‘]
迭代器iterator的next()函數被Python3廢棄,統一使用next(iterator)
raw_input函數被Python3廢棄,統一使用input函數
字典變數的has_key函數被Python廢棄,統一使用in關鍵詞
file函數被Python3廢棄,統一使用open來處理檔案,可以通過io.IOBase檢查檔案類型
apply函數被Python3廢棄
異常StandardError 被Python3廢棄,統一使用Exception
修改類差異
浮點數除法操作符/和//區別
- Python2:/是整數除法,//是小數除法
- Python3:/是小數除法,//是整數除法。
異常拋出和捕捉機制區別
raise IOError, "file error" #拋出異常except NameError, err: #捕捉異常
raise IOError("file error") #拋出異常except NameError as err: #捕捉異常
for迴圈中變數值區別
- Python2,for迴圈會修改外部相同名稱變數的值
i = 1print (‘comprehension: ‘, [i for i in range(5)])print (‘after: i =‘, i ) #i=4
Python3,for迴圈不會修改外部相同名稱變數的值
i = 1print (‘comprehension: ‘, [i for i in range(5)])print (‘after: i =‘, i ) #i=1
round函數傳回值區別
isinstance(round(15.5),int) #True
- Python3,round函數返回float類型值
isinstance(round(15.5),float) #True
比較操作符區別
11 < ‘test‘ #True
11 < ‘test‘ # TypeError: unorderable types: int() < str()
python2和python3的差異