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可以修复
原文地址:https://www.cnblogs.com/end-emptiness/p/12446650.html