python2和python3之間的差異和區別


本文目的為整理所有py2和3的差異,為學習或者代碼兼容/重構提供參考。

本文資料參考:

1、https://www.cnblogs.com/geogre123/p/10837462.html

2、lib2to3源碼

3、https://www.jianshu.com/p/ea54c2c7a3ea

4、https://www.cnblogs.com/zhaop8078/p/11363237.html

一、基本語法差異

相關字符 python2 python3 解決方法 備注

str.decode()

str.encode()

只有str類型,encode和decode返回結果都是str 返回結果是bytes   bytes是py3新增的類型

字符串默認編碼

len(str)

根據函數頭注釋編碼,如果是utf8編碼,一個中文算3個長度

默認均使用unicode編碼,一個中文算一個長度 len(str.encode("utf-8"))  
/ 3 / 2 -> 1 3 / 2 -> 1.5 使用//  
type: int 和 long

兩種整形

1L

統一為int

1

int  
sort sorted(iterable, cmp=None, key=None, reverse=False) sorted(iterable, key=None, reverse=False) 手動修改/不使用 移除了cmp參數
函數定義 不可以用中文定義 可以用中文    
raise raise E, V, T  raise E(V).with_traceback(T) lib2to3可以修復  
關鍵字參數       限定關鍵字參數 *后的變量必須加入名字=值
解包

>>> def unpacks(a, (b, c)): ... return a,b,c

>>> unpacks(1, (2,3)) (1, 2, 3)

>>> def unpacks(a, b):
... return a,b[0],b[1]

>>> unpacks(1, (2,3)) (1, 2, 3)

   
高級解包   高級解包操作:a,b,*rest = range(10)   關於解包,細碎的問題比較多
except except (Exception1, Exception2), target except (Exception1, Exception2) as target lib2to3可以修復  
import import導入自建包 導入系統包 from . import  
round

round返回值為浮點
且如果4舍5入兩端一樣遠,取距離0遠的值

round返回值為整形(如果第二個參數為空)。
且如果4舍5入兩端一樣遠,取偶數值

   
print 關鍵字 函數 lib2to3可以修復  
exec 關鍵字 函數 lib2to3可以修復  
metaclass __metaclass__  attribute metaclass  parameter lib2to3可以修復  
不等於 <> != lib2to3可以修復  
for ... in ... for i in 1, 2, 3 for i in (1, 2, 3) lib2to3可以修復  
StandardError   移除 lib2to3可以修復  
Class 舊式類和新式類兩種 移除舊式類    

二、移除的函數/關鍵字

python2 函數  python3 對應修改  備注
內建函數:coerce() def cmp(): return (a > b) - (a < b)  
內建函數:cmp() 使用numeric operator  
內建函數:raw_input() input() lib2to3可以修復
file() open(pathname) 如果是檢查類型,使用io.IOBase
關鍵字:execfile exec() lib2to3可以修復

range() return list

xrange() return genrator

range移除

xrange重命名為range

內建type:buffer 使用 memoryview
apply()  
long() int()
basestring() str()
intern() sys.intern()
內建函數:__nonzero__  
iterkeys()
itervalues()
iteritems()
keys()
values()
iterms()

三、函數返回值差異

函數 python2 python3 備注
filter() return list return iterator  lib2to3可以修復
zip() return list return iterator  
map() return list return iterator  

四、移除的成員函數

python2 python3 備注
iterator.next() next(iterator) lib2to3可以修復

sys.exitfunc

atexit  lib2to3可以修復
sys.maxint sys.maxsize

sys.exc_type

sys.exc_value

sys.exc_traceback

sys.exc_info()[0]

sys.exc_info()[1]

sys.exc_info()[2]

 os.getcwdu()  os.getcwd()
 itertools.(imap|ifilter|izip)  (map|filter|zip)
 itertools.ifilterfalse  itertools.filterfalse (bugs 2360-2363)
 

operator.isCallable(obj)
operator.sequenceIncludes(obj)
operator.isSequenceType(obj)
operator.isMappingType(obj)
operator.isNumberType(obj)
operator.repeat(obj, n)
operator.irepeat(obj, n)

 

hasattr(obj, '__call__')
operator.contains(obj)
isinstance(obj, collections.Sequence)
isinstance(obj, collections.Mapping)
isinstance(obj, numbers.Number)
operator.mul(obj, n)
operator.imul(obj, n)  

d.has_key(k) k in d
for x in f.xreadlines() for x in f

五、移除的成員屬性

python2 python3 備注

dict.iterkeys
dict.iteritems
dict.itervalues

iter(dict.keys)
iter(dict.items)
iter(dict.values)

lib2to3可以修復

d.viewkeys()
d.viewitems()
d.viewvalues()

d.keys()
d.items()
d.values()

iter.next next(iter)

f.func_closure
f.func_dict
f.func_doc
f.func_globals
f.func_name
f.func_defaults
f.func_code

f.__closure__
f.__dict__
f.__doc__
f.__globals__
f.__name__
f.__defaults__
f.__code__

method.im_func
method.im_self
method.im_class

method.__func__
method.__self__
method.__class__

   

六、移除的模塊

python2 python3 備注

dbm
tkFileDialog
__builtin__
ttk
dummy_thread
tkSimpleDialog
FileDialog
Tix
gdbm
robotparser
CGIHTTPServer
Cookie
cPickle
SocketServer
repr
Dialog
ScrolledText
cookielib
ConfigParser
httplib
markupbase
tkMessageBox
_winreg
DocXMLRPCServer
cStringIO
copy_reg
Tkdnd
SimpleHTTPServer
SimpleDialog
HTMLParser
BaseHTTPServer
tkCommonDialog
dumbdbm
UserList
UserString
Tkinter
tkFont
htmlentitydefs
SimpleXMLRPCServer
Queue
tkColorChooser
commands
thread
StringIO
xmlrpclib
Tkconstants
urlparse
dbhash

dbm.ndbm
tkinter.filedialog
builtins
tkinter.ttk
_dummy_thread
tkinter.simpledialog
tkinter.filedialog
tkinter.tix
dbm.gnu
urllib.robotparser
http.server
http.cookies
pickle
socketserver
reprlib
tkinter.dialog
tkinter.scrolledtext
http.cookiejar
configparser
http.client
_markupbase
tkinter.messagebox
winreg
xmlrpc.server
io
copyreg
tkinter.dnd
http.server
tkinter.simpledialog
html.parser
http.server
tkinter.commondialog
dbm.dumb
collections
collections
tkinter
tkinter.font
html.entities
xmlrpc.server
queue
tkinter.colorchooser
subprocess
_thread
io
xmlrpc.client
tkinter.constants
urllib.parse
dbm.bsd

lib2to3可以修復


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM