Python 3 為不相容 Python 2 的重大版本,以下彙整核心語法、內建函式、資料型別與模組差異,協助遷移與相容開發。
中國 = 'china'。| 項目 | Python 2 | Python 3 |
|---|---|---|
| 不等號 | <> 或 != | 僅 != |
| 反引號 | `` | 移除,改用 repr() |
| 新關鍵字 | - | as, with, True, False, None |
| 整數除法 | 3/2 == 1 | 3/2 == 1.5,整除用 // |
nonlocal | 無 | 新增,指派外層非全域變數 |
print | 陳述式 print 'hi' | 函式 print('hi') |
exec | 陳述式 | 函式 exec() |
raw_input | 讀取字串 | 移除,統一用 input() |
| 元組參數解包 | def f(a, (b, c)): | 移除 |
| 八進位字面值 | 0666 | 0o666 |
| 二進位字面值 | 無 | 0b101、bin() |
| 擴充解包 | 無 | a, b, *rest = seq |
super() | super(Class, self) | 無參數 super() |
ConfigParser → configparserQueue → queueSocketServer → socketserverurllib/urllib2 → urllib.request/parse/errorfrom __future__ import print_function, division, unicode_literals 在 Py2 模擬 Py3 行為。2to3 自動轉換工具輔助遷移。six 相容庫撰寫雙版本共用代碼。理解差異點,配合工具與測試,可平滑完成 Python 2 → 3 遷移。