專案馬上就要由python2遷移到python3環境所有就簡單總結下區別,個人覺得這些差不多,詳情見如下吧
核心類差異
Python3 對 Unicode 字符的原生支持
Python2 中使用 ASCII 碼作為默認編碼方式導致 string 有兩種型別 str 和 unicode,Python3 只 支持 unicode 的 string,Python2 和 Python3 位元組和字符對應關系為:

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
廢棄類差異
- exec 陳述句被 python3 廢棄,統一使用 exec 函式
- . execfile 陳述句被 Python3 廢棄,推薦使用 exec(open("./filename").read())
- 不相等運算子"<>"被 Python3 廢棄,統一使用"!="
- long 整數型別被 Python3 廢棄,統一使用 int
- xrange 函式被 Python3 廢棄,統一使用 range,Python3 中 range 的機制也進行修改并提高 了大資料集生成效率
- raw_input 函式被 Python3 廢棄,統一使用 input 函式
- 字典變數的 has_key 函式被 Python 廢棄,統一使用 in 關鍵詞
- apply 函式被 Python3 廢棄
- 例外 StandardError 被 Python3 廢棄,統一使用 Exception
- file 函式被 Python3 廢棄,統一使用 open 來處理檔案,可以通過 io.IOBase 檢查檔案型別
- 迭代器 iterator 的 next()函式被 Python3 廢棄,統一使用 next(iterator)
- 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']
部分模塊的修改
urillib和urllib2
| Python2 | Python3 |
|---|---|
| urllib2.urlopen() | urllib.request.urlopen() |
| urllib2.Request() | urllib.request.Request() |
| htmllib.HTMLParser | html.parser.HTMLParse |
| httplib | http.client |
python3將python2中的urllib2、urlparse、robotparser并入了urllib模塊,并且修改了urllib模塊,其中包含了5個子模塊,每個子模塊中的常用方法如下:
| 模塊名 | 常用方法 |
|---|---|
| urllib.error | ContentTooShortError、URLError、HTTPError |
| urllib.parse | urlparse、_splitparams、urlsplit、urlunparse、urlunsplit、urljoin、urldefrag、unquote_to_bytes、unquote、parse_qs、parse_qsl、unquote_plus、quote、quote_plus、quote_from_bytes、urlencode、to_bytes、unwrap、splittype、splithost、splituser、splitpasswd、splitport |
| urllib.request | install_opener、urlretrieve、 urlcleanup、 request_host、 build_opener、 _parse_proxy、 parse_keqv_list、 parse_http_list、 _safe_gethostbyname、 ftperrors、 noheaders、 getproxies_environment、 proxy_bypass_environment、 _proxy_bypass_macosx_sysconf、 Request |
| urllib.response | addbase、 addclosehook、 addinfo、 addinfourl |
| urllib.robotparser | RobotFileParser |
修改類差異
浮點數除法運算子“/”和“//”的區別
“ / ”:
Python2:若為兩個整形數進行運算,結果為整形,但若兩個數中有一個為浮點數,則結果為 浮點數;
Python3:為真除法,運算結果不再根據參加運算的數的型別,
“//”:
Python2:
回傳小于除法運算結果的最大整數;從型別上講,與"/"運算子回傳型別邏輯一致,
Python3:和 Python2 運算結果一樣,
例外拋出和捕捉機制區別
Python2
- raise IOError, "file error" #拋出例外
- except NameError, err: #捕捉例外
Python3
- raise IOError("file error") #拋出例外
- except NameError as err: #捕捉例外
for 回圈中變數值區別
Python2,for 回圈會修改外部相同名稱變數的值
i = 1
print ('comprehension: ', [i for i in range(5)])
print ('after: i =', i ) #i=4
Python3,for 回圈不會修改外部相同名稱變數的值
i = 1
print ('comprehension: ', [i for i in range(5)])
print ('after: i =', i
round 函式回傳值區別
Python2,round 函式回傳 float 型別值
>>> isinstance(round(15.5),float)
True
>>> round(15.5)
16.0
Python3,round 函式回傳 int 型別值
>>> isinstance(round(15.5),int)
True
>>> round(15.5)
16
比較運算子區別
Python2 中任意兩個物件都可以比較
>>> 11 < 'test'
True
Python3 中只有同一資料型別的物件可以比較
>>> 11 < 'test'
File "<stdin>", line 1
11 < 'test'
^
IndentationError: unexpected indent
工具安裝問題
windows 環境
Python2 無法安裝 mysqlclient,
Python3 無法安裝 MySQL-python、 flup、functools32、 Gooey、Pywin32、 webencodings,matplotlib 在 python3 環境中安裝報錯:The following required packages can not be built:freetype, png,需要手動下載安裝原始碼包安裝解決, scipy 在 Python3 環境中安裝報錯,numpy.distutils.system_info.NotFoundError,需要自己手 工下載對應的安裝包,依賴 numpy,pandas 必須嚴格根據 python 版本、作業系統、64 位與否,運行 matplotlib 后發現基礎包 numpy+mkl 安裝失敗,需要自己下載,國內暫無下載源
centos 環境下
Python2 無法安裝 mysql-python 和 mysqlclient 包,報錯:EnvironmentError: mysql_config not found,解決方案是安裝 mysql-devel 包解決,使用 matplotlib 報錯:no module named _tkinter, 安裝 Tkinter、tk-devel、tc-devel 解決, pywin32 也無法在 centos 環境下安裝,
學習鏈接
Python3與Python2有哪些區別?
和羞走,倚門回首,卻把青梅嗅, ------李清照
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/220640.html
標籤:python
上一篇:第二章 tensor和梯度計算
下一篇:python學習
