Python2.x和3.x的主要區別
版本說明
Python 2.6作為一個過渡版本,基本使用了Python 2.x的語法和庫,同時考慮了向Python 3.0的遷移,允許使用部分Python 3.0的語法與函式。
除非為了使用舊的Python2.x專案程式碼或只支援2.x的第三方庫,否則不推薦使用2.x進行程式設計
死人的print函式
Python 2.6與Python 2.7裡面,以下三種形式是等價的:
print "fish" print ("fish") #注意print後面有個空格 print("fish") #print()不能帶有任何其它引數
但python3.x只能使用後兩者,print語句被python3廢棄,只能使用print函式
Unicode
Python3中字串是Unicode (utf-8)編碼,支援中文做識別符號。
python2中是ASCII編碼,需要更改字符集才能正常支援中文,所以在.py檔案中會看到#-- coding: UTF-8 - -。
#python3中 >>> 中國 = 'china' >>>print(中國) china #python2中 >>> str = "我愛北京天安門" >>> str '\xe6\x88\x91\xe7\x88\xb1\xe5\x8c\x97\xe4\xba\xac\xe5\xa4\xa9\xe5\xae\x89\xe9\x97\xa8' >>> str = u"我愛北京天安門" >>> str u'\u6211\u7231\u5317\u4eac\u5929\u5b89\u95e8'
除法運算
單斜槓/,Python2中整數相除得整數,浮點小數相除得浮點;Python3中結果總是浮點數。
#python3 >>print(10/5) 2.0
雙斜槓//,Python2和3相同,都是除法結果去掉小數部分
>>print(10//3) 3
異常處理
Python2中try:...except ERR,e:...,在Python3中改為了try:...except ERR as e:...
#Python3 try: open('a.txt','r') except Exception as e: print(e) #這裡也不要使用e.message
python 2中觸發異常可以用raise IOError, "file error"或raise IOError("file error")兩種方式。
python 3中觸發異常只能用raise IOError("file error")。
異常StandardError 被Python3廢棄,統一使用Exception
xrange和range
Python3中不再使用xrange方法,只有range方法
range在Python2中返回列表,而在Python3中返回range可迭代物件
a=range(10) print(a) print(list(a))
輸出
range(0, 10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
八進位制字面量
Python3中只能使用0o...格式,對於01000格式將丟擲錯誤,而在Python2中兩種都能使用
>>> 01000 File "<stdin>", line 1 01000 ^ SyntaxError: invalid token >>> 0o1000 512
不等運算子
在Python2中有兩個不等運算子!=和<>,在Python3中去掉了<>,只有!=符號表示不等。
repr
在Python2中雙反引號``可以替代repr函式,在Python3中去掉了雙反引號的表是方法,只能用repr方法
模組改名
StringIO模組現在被合併到新的io模組內。 new, md5, gopherlib等模組被刪除。
httplib, BaseHTTPServer, CGIHTTPServer, SimpleHTTPServer, Cookie, cookielib被合併到http包內。
取消了exec語句,只剩下exec()函式。
long型別
在Python2中long是比int取值範圍更大的整數,Python3中取消了long型別,int的取值範圍擴大到之前的long類型範圍
bytes型別
Python3新增了bytes型別,使用b開頭的字串定義:
>>> 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'
dict型別
Python3中dict的.keys()、.items 和.values()方法返回迭代器,而之前的iterkeys()等函式都被廢棄。
同時去掉的還有 dict.has_key(),可以用in來代替。
di={ 'a':1, 'b':2, 'c':3 } for item in d.items(): print(item) print('c' in di)
輸出
('gggg', {'a1': 1}) ('b', 12) True
next()函式和.next()方法
my_generator = (letter for letter in 'abcdefg')
python 2中可以用next(my_generator) 和 my_generator.next() 兩種方式。
python 3中只能用 next(my_generator)這種方式。
列表推導
不再支援[n for n in a,b]
語法,改為[n for n in (a,b)]
或[n for n in [a,b]]
a=1 b=2 c=[n for n in [a,b]] print(c)
輸出[1,2]
input
python 2 中通過input 輸入的型別是 int,只有通過 raw_input()輸入的型別才是str.
python 3中通過input輸入的型別都是是str,去掉了row_input()方法。
比較符
Python 2 中任意兩個物件都可以比較,11 < 'test'
返回True
Python 3中只有同一資料型別的物件可以比較,11 < 'test'
報錯,需要呼叫正則判斷,改為import re;11 < int('test') if re.compile('^[0-9]+$').match('test') else 0
否則就報錯
其他
exec語句被python3廢棄,統一使用exec函式
execfile語句被Python3廢棄,推薦使用exec(open("./filename").read())
Python3中這些方法不再返回list物件:dictionary關聯的keys()、values()、items(),zip(),map(),filter(),但是可以通過list強行轉換
迭代器iterator的next()函式被Python3廢棄,統一使用next(iterator)
file函式被Python3廢棄,統一使用open來處理檔案,可以通過io.IOBase檢查檔案型別
apply函式被Python3廢棄
更多內容請你在實踐中慢慢體會。