目录
python2 和 python3 的差异与兼容一览表
python 2 | python 3 | python 2 & python 3 | |
---|---|---|---|
1 |
long,int |
int |
six.integer_types |
2 |
basestring |
str |
six.string_type |
3 |
unicode |
str |
six.text_type |
4 |
str |
bytes |
six.binary_type |
|
|
|
|
5 |
<>, != |
!= |
!= |
6 |
__comp__() |
__eq__, __ne__, __lt__, __le__, __gt__, __ge__ |
|
7 |
3 / 2 = 1 |
3 // 2 = 1 , 3 / 2 = 1.5 |
|
8 |
round(16.5) =17, round(17.5) = 18 |
round(16.5) =16, round(17.5) = 18 |
|
9 |
raw_input(), input() |
input() |
input() |
10 |
print |
print() |
if six.PY3 … else ... |
11 |
file(), open() |
open() |
open() |
12 |
exec |
exec() |
if six.PY3 … else ... |
13 |
execfile('filename') |
exec(compile(open('filename').read(),'filename','exec')) |
if six.PY3 … else ... |
14 |
xrange() , range() 不需要生成list对象时 |
range() |
six.moves.xrange() |
15 |
range():需要生成 list 时 |
list(range()) |
list(six.moves.xrange) |
16 |
has_key() |
in |
in |
17 |
dict.iteritems() , dict.items() 只读时 |
dict.items() |
six.iteritems(dict) |
dict.items() 需要修改时 |
list(dict.items()) |
list(six.iteritems(dict)) |
|
18 |
dict.iterkeys() , dict.keys() 只读时 |
dict.keys() |
six.iterkeys(dict) |
dict.keys() 需要修改时 |
list(dict.keys()) |
list(six.iterkeys()) |
|
for key in dict.iterkeys(): |
for key in dict: |
for key in dict: |
|
19 |
dict.itervalues() , dict.values() 只读时 |
dict.values() |
six.itervalues(dict) |
dict.values() 需要修改时 |
list(dict.values()) |
list(six.itervalues(dict) |
|
21 |
itertools.izip() , zip() 只读时 |
zip() |
six.moves.zip() |
zip() 需要修改时 , |
list(zip()) |
list(six.moves.zip() ) |
|
22 |
itertools.imap() , map() 只读时 |
map() |
six.moves.map() |
map() 需要修改时 |
list(map()) |
list(six.moves.map()) |
|
23 |
Itertools.ifilter() , filter() 只读时 |
filter() |
six.moves.filter() |
filter() 需要修改时 |
list(filter()) |
list(six.moves.filter()) |
|
24 | 迭代器 next() 函数和 .next() 方法 | 迭代器 next() 函数 | 迭代器 next() 函数 |
25 | raise IOError, "file error" |
raise IOError("file error") | raise IOError("file error") |
26 | try: ...except NameError, err: |
try: ...except NameError as err: | try: ...except NameError as err: |
python2 和 python3 的差异与兼容详解
py3 的更改:py3 的新功能
要做到兼容 py2 和 py3,我们需要了解两个模块。
- __future__ ,py3 引入了一些与 py2 不兼容的关键字和功能,这些关键字和功能可以通过 py2 中的内置 __future__ 模块导入。
feature |
optional in |
mandatory in |
effect |
---|---|---|---|
nest |