Python 2.7.x 和 3.x 版本的重要区别

许多Python初学者都会问:我应该学习哪个版本的Python。对于这个问题,我的回答通常是“先选择一个最适合你的Python教程,教程中使用哪个版本的Python,你就用那个版本。等学得差不多了,再来研究不同版本之间的差别”。

但如果想要用Python开发一个新项目,那么该如何选择Python版本呢?我可以负责任的说,大部分Python库都同时支持Python 2.7.x和3.x版本的,所以不论选择哪个版本都是可以的。但为了在使用Python时避开某些版本中一些常见的陷阱,或需要移植某个Python项目时,依然有必要了解一下Python两个常见版本之间的主要区别。

目录

__future__模块

[回到目录]

Python 3.x引入了一些与Python 2不兼容的关键字和特性,在Python 2中,可以通过内置的__future__模块导入这些新内容。如果你希望在Python 2环境下写的代码也可以在Python 3.x中运行,那么建议使用__future__模块。例如,如果希望在Python 2中拥有Python 3.x的整数除法行为,可以通过下面的语句导入相应的模块。

Python

from __future__ import division


1


from __future__ import division

下表列出了__future__中其他可导入的特性:


特性


可选版本


强制版本


  效果


nested_scopes


2.1.0b1


2.2


PEP 227:
Statically Nested Scopes


generators


2.2.0a1


2.3


PEP
255
:
Simple Generators


division


2.2.0a2


3.0


PEP
238
:
Changing the Division Operator


absolute_import


2.5.0a1


3.0


PEP
328
:
Imports: Multi-Line and Absolute/Relative


with_statement


2.5.0a1


2.6


PEP
343
:
The “with” Statement


print_function


2.6.0a2


3.0


PEP
3105
:
Make print a function


unicode_literals


2.6.0a2


3.0


PEP
3112
:
Bytes literals in Python 3000

(来源: https://docs.python.org/2/library/future.html)

示例:

Python

from platform import python_version


1


from platform import python_version

print函数

[回到目录]

虽然print语法是Python 3中一个很小的改动,且应该已经广为人知,但依然值得提一下:Python 2中的print语句被Python 3中的print()函数取代,这意味着在Python 3中必须用括号将需要输出的对象括起来。

在Python 2中使用额外的括号也是可以的。但反过来在Python 3中想以Python2的形式不带括号调用print函数时,会触发SyntaxError。

Python 2

Python

print ‘Python‘, python_version()
print ‘Hello, World!‘
print(‘Hello, World!‘)
print "text", ; print ‘print more text on the same line‘


1

2

3

4


print ‘Python‘, python_version()

print ‘Hello, World!‘

print(‘Hello, World!‘)

print "text", ; print ‘print more text on the same line‘

Python

Python 2.7.6
Hello, World!
Hello, World!
text print more text on the same line


1

2

3

4


Python 2.7.6

Hello, World!

Hello, World!

text print more text on the same line

Python 3

Python

print(‘Python‘, python_version())
print(‘Hello, World!‘)

print("some text,", end="")
print(‘ print more text on the same line‘)


1

2

3

4

5


print(‘Python‘, python_version())

print(‘Hello, World!‘)

print("some text,", end="")

print(‘ print more text on the same line‘)

Python

Python 3.4.1
Hello, World!
some text, print more text on the same line


1

2

3


Python 3.4.1

Hello, World!

some text, print more text on the same line

Python

print ‘Hello, World!‘


1


print ‘Hello, World!‘

Python

File "<ipython-input-3-139a7c5835bd>", line 1
print ‘Hello, World!‘
^
SyntaxError: invalid syntax


1

2

3

4


File "<ipython-input-3-139a7c5835bd>", line 1

print ‘Hello, World!‘

^

SyntaxError: invalid syntax

注意:

在Python中,带不带括号输出”Hello World”都很正常。但如果在圆括号中同时输出多个对象时,就会创建一个元组,这是因为在Python 2中,print是一个语句,而不是函数调用。

Python

print ‘Python‘, python_version()
print(‘a‘, ‘b‘)
print ‘a‘, ‘b‘


1

2

3


print ‘Python‘, python_version()

print(‘a‘, ‘b‘)

print ‘a‘, ‘b‘

Python

Python 2.7.7
(‘a‘, ‘b‘)
a b


1

2

3


Python 2.7.7

(‘a‘, ‘b‘)

a b

整数除法

[回到目录]

由于人们常常会忽视Python 3在整数除法上的改动(写错了也不会触发Syntax Error),所以在移植代码或在Python 2中执行Python 3的代码时,需要特别注意这个改动。

所以,我还是会在Python 3的脚本中尝试用float(3)/2或 3/2.0代替3/2,以此来避免代码在Python 2环境下可能导致的错误(或与之相反,在Python 2脚本中用from __future__ import division来使用Python 3的除法)。

Python 2

Python

print ‘Python‘, python_version()
print ‘3 / 2 =‘, 3 / 2
print ‘3 // 2 =‘, 3 // 2
print ‘3 / 2.0 =‘, 3 / 2.0
print ‘3 // 2.0 =‘, 3 // 2.0


1

2

3

4

5


print ‘Python‘, python_version()

print ‘3 / 2 =‘, 3 / 2

print ‘3 // 2 =‘, 3 // 2

print ‘3 / 2.0 =‘, 3 / 2.0

print ‘3 // 2.0 =‘, 3 // 2.0

Python

Python 2.7.6
3 / 2 = 1
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0


1

2

3

4

5


Python 2.7.6

3 / 2 = 1

3 // 2 = 1

3 / 2.0 = 1.5

3 // 2.0 = 1.0

Python 3

Python

print(‘Python‘, python_version())
print(‘3 / 2 =‘, 3 / 2)
print(‘3 // 2 =‘, 3 // 2)
print(‘3 / 2.0 =‘, 3 / 2.0)
print(‘3 // 2.0 =‘, 3 // 2.0)


1

2

3

4

5


print(‘Python‘, python_version())

print(‘3 / 2 =‘, 3 / 2)

print(‘3 // 2 =‘, 3 // 2)

print(‘3 / 2.0 =‘, 3 / 2.0)

print(‘3 // 2.0 =‘, 3 // 2.0)

Python

Python 3.4.1
3 / 2 = 1.5
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0


1

2

3

4

5


Python 3.4.1

3 / 2 = 1.5

3 // 2 = 1

3 / 2.0 = 1.5

3 // 2.0 = 1.0

Unicode

[回到目录]

Python 2有基于ASCII的str()类型,其可通过单独的unicode()函数转成unicode类型,但没有byte类型。

而在Python 3中,终于有了Unicode(utf-8)字符串,以及两个字节类:bytes和bytearrays。

Python 2

Python

print ‘Python‘, python_version()


1


print ‘Python‘, python_version()

Python

Python 2.7.6


1


Python 2.7.6

Python

print type(unicode(‘this is like a python3 str type‘))


1


print type(unicode(‘this is like a python3 str type‘))

Python

<type ‘unicode‘>


1


<type ‘unicode‘>

Python

print type(b‘byte type does not exist‘)


1


print type(b‘byte type does not exist‘)

Python

<type ‘str‘>


1


<type ‘str‘>

Python

print ‘they are really‘ + b‘ the same‘


1


print ‘they are really‘ + b‘ the same‘

Python

they are really the same


1


they are really the same

Python

print type(bytearray(b‘bytearray oddly does exist though‘))


1


print type(bytearray(b‘bytearray oddly does exist though‘))

Python

<type ‘bytearray‘>


1


<type ‘bytearray‘>

Python 3

Python

print(‘Python‘, python_version())
print(‘strings are now utf-8 u03BCnicou0394é!‘)


1

2


print(‘Python‘, python_version())

print(‘strings are now utf-8 u03BCnicou0394é!‘)

Python

Python 3.4.1
strings are now utf-8 μnicoΔé!


1

2


Python 3.4.1

strings are now utf-8 μnicoΔé!

Python

print(‘Python‘, python_version(), end="")
print(‘ has‘, type(b‘ bytes for storing data‘))


1

2


print(‘Python‘, python_version(), end="")

print(‘ has‘, type(b‘ bytes for storing data‘))

Python

Python 3.4.1 has <class ‘bytes‘>


1


Python 3.4.1 has <class ‘bytes‘>

Python

print(‘and Python‘, python_version(), end="")
print(‘ also has‘, type(bytearray(b‘bytearrays‘)))


1

2


print(‘and Python‘, python_version(), end="")

print(‘ also has‘, type(bytearray(b‘bytearrays‘)))

Python

and Python 3.4.1 also has <class ‘bytearray‘>


1


and Python 3.4.1 also has <class ‘bytearray‘>

Python

‘note that we cannot add a string‘ + b‘bytes for data‘


1


‘note that we cannot add a string‘ + b‘bytes for data‘

Python

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-13-d3e8942ccf81> in <module>()
----> 1 ‘note that we cannot add a string‘ + b‘bytes for data‘

TypeError: Can‘t convert ‘bytes‘ object to str implicitly


1

2

3

4

5

6


---------------------------------------------------------------------------

TypeError Traceback (most recent call last)

<ipython-input-13-d3e8942ccf81> in <module>()

----> 1 ‘note that we cannot add a string‘ + b‘bytes for data‘

TypeError: Can‘t convert ‘bytes‘ object to str implicitly

xrange

[回到目录]

在Python 2.x中,经常会用xrange()创建一个可迭代对象,通常出现在“for循环”或“列表/集合/字典推导式”中。

这种行为与生成器非常相似(如”惰性求值“),但这里的xrange-iterable无尽的,意味着可能在这个xrange上无限迭代。

由于xrange的“惰性求知“特性,如果只需迭代一次(如for循环中),range()通常比xrange()快一些。不过不建议在多次迭代中使用range(),因为range()每次都会在内存中重新生成一个列表。

在Python 3中,range()的实现方式与xrange()函数相同,所以就不存在专用的xrange()(在Python 3中使用xrange()会触发NameError)。

Python

import timeit

n = 10000
def test_range(n):
return for i in range(n):
pass

def test_xrange(n):
for i in xrange(n):
pass


1

2

3

4

5

6

7

8

9

10


import timeit

n = 10000

def test_range(n):

return for i in range(n):

pass

def test_xrange(n):

for i in xrange(n):

pass

Python 2

Python

print ‘Python‘, python_version()

print ‘ntiming range()‘
%timeit test_range(n)

print ‘nntiming xrange()‘
%timeit test_xrange(n)


1

2

3

4

5

6

7

8


print ‘Python‘, python_version()

print ‘ntiming range()‘

%timeit test_range(n)

print ‘nntiming xrange()‘

%timeit test_xrange(n)

Python

Python 2.7.6

timing range()
1000 loops, best of 3: 433 µs per loop

timing xrange()
1000 loops, best of 3: 350 µs per loop


1

2

3

4

5

6

7


Python 2.7.6

timing range()

1000 loops, best of 3: 433 µs per loop

timing xrange()

1000 loops, best of 3: 350 µs per loop

Python 3

Python

print(‘Python‘, python_version())

print(‘ntiming range()‘)
%timeit test_range(n)


1

2

3

4


print(‘Python‘, python_version())

print(‘ntiming range()‘)

%timeit test_range(n)

Python

Python 3.4.1

timing range()
1000 loops, best of 3: 520 µs per loop


1

2

3

4


Python 3.4.1

timing range()

1000 loops, best of 3: 520 µs per loop

Python

print(xrange(10))


1


print(xrange(10))

Python

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
in ()
----> 1 print(xrange(10))

NameError: name ‘xrange‘ is not defined


1

2

3

4

5

6


---------------------------------------------------------------------------

NameError Traceback (most recent call last)

in ()

----> 1 print(xrange(10))

NameError: name ‘xrange‘ is not defined

Python 3中的range对象中的__contains__方法

另一个值得一提的是,在Python 3.x中,range有了一个新的__contains__方法。__contains__方法可以有效的加快Python 3.x中整数和布尔型的“查找”速度。

Python

x = 10000000
def val_in_range(x, val):
return val in range(x)

def val_in_xrange(x, val):
return val in xrange(x)

print(‘Python‘, python_version())
assert(val_in_range(x, x/2) == True)
assert(val_in_range(x, x//2) == True)
%timeit val_in_range(x, x/2)
%timeit val_in_range(x, x//2)


1

2

3

4

5

6

7

8

9

10

11

12

13


x = 10000000

def val_in_range(x, val):

return val in range(x)

def val_in_xrange(x, val):

return val in xrange(x)

print(‘Python‘, python_version())

assert(val_in_range(x, x/2) == True)

assert(val_in_range(x, x//2) == True)

%timeit val_in_range(x, x/2)

%timeit val_in_range(x, x//2)

Python

Python 3.4.1
1 loops, best of 3: 742 ms per loop
1000000 loops, best of 3: 1.19 µs per loop


1

2

3


Python 3.4.1

1 loops, best of 3: 742 ms per loop

1000000 loops, best of 3: 1.19 µs per loop

根据上面的timeit的结果,查找整数比查找浮点数要快大约6万倍。但由于Python 2.x中的range或xrange没有__contains__方法,所以在Python 2中的整数和浮点数的查找速度差别不大。

Python

print ‘Python‘, python_version()

assert(val_in_xrange(x, x/2.0) == True)
assert(val_in_xrange(x, x/2) == True)
assert(val_in_range(x, x/2) == True)
assert(val_in_range(x, x//2) == True)
%timeit val_in_xrange(x, x/2.0)
%timeit val_in_xrange(x, x/2)
%timeit val_in_range(x, x/2.0)
%timeit val_in_range(x, x/2)


1

2

3

4

5

6

7

8

9

10

11

12

13


print ‘Python‘, python_version()

assert(val_in_xrange(x, x/2.0) == True)

assert(val_in_xrange(x, x/2) == True)

assert(val_in_range(x, x/2) == True)

assert(val_in_range(x, x//2) == True)

%timeit val_in_xrange(x, x/2.0)

%timeit val_in_xrange(x, x/2)

%timeit val_in_range(x, x/2.0)

%timeit val_in_range(x, x/2)

Python

Python 2.7.7
1 loops, best of 3: 285 ms per loop
1 loops, best of 3: 179 ms per loop
1 loops, best of 3: 658 ms per loop
1 loops, best of 3: 556 ms per loop


1

2

3

4

5


Python 2.7.7

1 loops, best of 3: 285 ms per loop

1 loops, best of 3: 179 ms per loop

1 loops, best of 3: 658 ms per loop

1 loops, best of 3: 556 ms per loop

下面的代码证明了Python 2.x中没有__contain__方法:

Python

print(‘Python‘, python_version())
range.__contains__


1

2


print(‘Python‘, python_version())

range.__contains__

Python

Python 3.4.1
<slot wrapper ‘__contains__‘ of ‘range‘ objects


1

2


Python 3.4.1

<slot wrapper ‘__contains__‘ of ‘range‘ objects

Python

print(‘Python‘, python_version())
range.__contains__


1

2


print(‘Python‘, python_version())

range.__contains__

Python

Python 2.7.7
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-7-05327350dafb> in <module>()
1 print ‘Python‘, python_version()
----> 2 range.__contains__

AttributeError: ‘builtin_function_or_method‘ object has no attribute ‘__contains__‘


1

2

3

4

5

6

7

8


Python 2.7.7

---------------------------------------------------------------------------

AttributeError Traceback (most recent call last)

<ipython-input-7-05327350dafb> in <module>()

1 print ‘Python‘, python_version()

----> 2 range.__contains__

AttributeError: ‘builtin_function_or_method‘ object has no attribute ‘__contains__‘

Python

print(‘Python‘, python_version())
xrange.__contains__


1

2


print(‘Python‘, python_version())

xrange.__contains__

Python

Python 2.7.7

---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
in ()
1 print ‘Python‘, python_version()
----> 2 xrange.__contains__

AttributeError: type object ‘xrange‘ has no attribute ‘__contains__‘


1

2

3

4

5

6

7

8

9


Python 2.7.7

---------------------------------------------------------------------------

AttributeError Traceback (most recent call last)

in ()

1 print ‘Python‘, python_version()

----> 2 xrange.__contains__

AttributeError: type object ‘xrange‘ has no attribute ‘__contains__‘

关于Python 2中xrange()与Python 3中range()之间的速度差异的一点说明:

有读者指出了Python 3中的range()和Python 2中xrange()执行速度有差异。由于这两者的实现方式相同,因此理论上执行速度应该也是相同的。这里的速度差别仅仅是因为Python 3的总体速度就比Python 2慢。

Python

def test_while():
i = 0
while i < 20000:
i += 1
return


1

2

3

4

5


def test_while():

i = 0

while i < 20000:

i += 1

return

Python

print(‘Python‘, python_version())
%timeit test_while()


1

2


print(‘Python‘, python_version())

%timeit test_while()

Python

Python 3.4.1
%timeit test_while()
100 loops, best of 3: 2.68 ms per loop


1

2

3

4


Python 3.4.1

%timeit test_while()

100 loops, best of 3: 2.68 ms per loop

Python

print ‘Python‘, python_version()
%timeit test_while()


1

2


print ‘Python‘, python_version()

%timeit test_while()

Python

Python 2.7.6
1000 loops, best of 3: 1.72 ms per loop


1

2


Python 2.7.6

1000 loops, best of 3: 1.72 ms per loop

触发异常

[回到目录]

Python 2支持新旧两种异常触发语法,而Python 3只接受带括号的的语法(不然会触发SyntaxError):

Python 2

Python

print ‘Python‘, python_version()


1


print ‘Python‘, python_version()

Python

Python 2.7.6


1


Python 2.7.6

Python

raise IOError, "file error"


1


raise IOError, "file error"

Python

---------------------------------------------------------------------------
IOError Traceback (most recent call last)
<ipython-input-8-25f049caebb0> in <module>()
----> 1 raise IOError, "file error"

IOError: file error


1

2

3

4

5

6


---------------------------------------------------------------------------

IOError Traceback (most recent call last)

<ipython-input-8-25f049caebb0> in <module>()

----> 1 raise IOError, "file error"

IOError: file error

Python

raise IOError("file error")


1


raise IOError("file error")

Python

---------------------------------------------------------------------------
IOError Traceback (most recent call last)
<ipython-input-9-6f1c43f525b2> in <module>()
----> 1 raise IOError("file error")

IOError: file error


1

2

3

4

5

6


---------------------------------------------------------------------------

IOError Traceback (most recent call last)

<ipython-input-9-6f1c43f525b2> in <module>()

----> 1 raise IOError("file error")

IOError: file error

Python 3

Python

print(‘Python‘, python_version())


1


print(‘Python‘, python_version())

Python

Python 3.4.1


1


Python 3.4.1

Python

raise IOError, "file error"


1


raise IOError, "file error"

Python

File "<ipython-input-10-25f049caebb0>", line 1
raise IOError, "file error"
^
SyntaxError: invalid syntax
The proper way to raise an exception in Python 3:


1

2

3

4

5


File "<ipython-input-10-25f049caebb0>", line 1

raise IOError, "file error"

^

SyntaxError: invalid syntax

The proper way to raise an exception in Python 3:

Python

print(‘Python‘, python_version())
raise IOError("file error")


1

2


print(‘Python‘, python_version())

raise IOError("file error")

Python

Python 3.4.1

---------------------------------------------------------------------------
OSError Traceback (most recent call last)
<ipython-input-11-c350544d15da> in <module>()
1 print(‘Python‘, python_version())
----> 2 raise IOError("file error")

OSError: file error


1

2

3

4

5

6

7

8

9


Python 3.4.1

---------------------------------------------------------------------------

OSError Traceback (most recent call last)

<ipython-input-11-c350544d15da> in <module>()

1 print(‘Python‘, python_version())

----> 2 raise IOError("file error")

OSError: file error

异常处理

[回到目录]

Python 3中的异常处理也发生了一点变化。在Python 3中必须使用“as”关键字。

Python 2

Python

print ‘Python‘, python_version()
try:
let_us_cause_a_NameError
except NameError, err:
print err, ‘--> our error message‘


1

2

3

4

5


print ‘Python‘, python_version()

try:

let_us_cause_a_NameError

except NameError, err:

print err, ‘--> our error message‘

Python

Python 2.7.6
name ‘let_us_cause_a_NameError‘ is not defined --> our error message


1

2


Python 2.7.6

name ‘let_us_cause_a_NameError‘ is not defined --> our error message

Python 3

Python

print(‘Python‘, python_version())
try:
let_us_cause_a_NameError
except NameError as err:
print(err, ‘--> our error message‘)


1

2

3

4

5


print(‘Python‘, python_version())

try:

let_us_cause_a_NameError

except NameError as err:

print(err, ‘--> our error message‘)

Python

Python 3.4.1
name ‘let_us_cause_a_NameError‘ is not defined --> our error message


1

2


Python 3.4.1

name ‘let_us_cause_a_NameError‘ is not defined --> our error message

next()函数和.next()方法

[回到目录]

由于会经常用到next()(.next())函数(方法),所以还要提到另一个语法改动(实现方面也做了改动):在Python 2.7.5中,函数形式和方法形式都可以使用,而在Python 3中,只能使用next()函数(试图调用.next()方法会触发AttributeError)。

Python 2

Python

print ‘Python‘, python_version()
my_generator = (letter for letter in ‘abcdefg‘)
next(my_generator)
my_generator.next()


1

2

3

4


print ‘Python‘, python_version()

my_generator = (letter for letter in ‘abcdefg‘)

next(my_generator)

my_generator.next()

Python

Python 2.7.6
‘b‘


1

2


Python 2.7.6

‘b‘

Python 3

Python

print(‘Python‘, python_version())
my_generator = (letter for letter in ‘abcdefg‘)
next(my_generator)


1

2

3


print(‘Python‘, python_version())

my_generator = (letter for letter in ‘abcdefg‘)

next(my_generator)

Python

Python 3.4.1
‘a‘


1

2


Python 3.4.1

‘a‘

Python

my_generator.next()


1


my_generator.next()

Python

---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-14-125f388bb61b> in <module>()
----> 1 my_generator.next()

AttributeError: ‘generator‘ object has no attribute ‘next‘


1

2

3

4

5

6


---------------------------------------------------------------------------

AttributeError Traceback (most recent call last)

<ipython-input-14-125f388bb61b> in <module>()

----> 1 my_generator.next()

AttributeError: ‘generator‘ object has no attribute ‘next‘

For循环变量与全局命名空间泄漏

[回到目录]

好消息是:在Python 3.x中,for循环中的变量不再会泄漏到全局命名空间中了!

这是Python 3.x中做的一个改动,在“What’s New In Python 3.0”中有如下描述:

“列表推导不再支持[… for var in item1, item2, …]这样的语法,使用[… for var in (item1, item2, …)]代替。还要注意列表推导有不同的语义:现在列表推导更接近list()构造器中的生成器表达式这样的语法糖,特别要注意的是,循环控制变量不会再泄漏到循环周围的空间中了。”

Python 2

Python

print ‘Python‘, python_version()

i = 1
print ‘before: i =‘, i

print ‘comprehension: ‘, [i for i in range(5)]

print ‘after: i =‘, i


1

2

3

4

5

6

7

8


print ‘Python‘, python_version()

i = 1

print ‘before: i =‘, i

print ‘comprehension: ‘, [i for i in range(5)]

print ‘after: i =‘, i

Python

Python 2.7.6
before: i = 1
comprehension: [0, 1, 2, 3, 4]
after: i = 4


1

2

3

4


Python 2.7.6

before: i = 1

comprehension: [0, 1, 2, 3, 4]

after: i = 4

Python 3

Python

print(‘Python‘, python_version())

i = 1
print(‘before: i =‘, i)

print(‘comprehension:‘, [i for i in range(5)])

print(‘after: i =‘, i)


1

2

3

4

5

6

7

8


print(‘Python‘, python_version())

i = 1

print(‘before: i =‘, i)

print(‘comprehension:‘, [i for i in range(5)])

print(‘after: i =‘, i)

Python

Python 3.4.1
before: i = 1
comprehension: [0, 1, 2, 3, 4]
after: i = 1


1

2

3

4


Python 3.4.1

before: i = 1

comprehension: [0, 1, 2, 3, 4]

after: i = 1

比较无序类型

[回到目录]

Python 3中另一个优秀的改动是,如果我们试图比较无序类型,会触发一个TypeError。

Python 2

Python

print ‘Python‘, python_version()
print "[1, 2] > ‘foo‘ = ", [1, 2] > ‘foo‘
print "(1, 2) > ‘foo‘ = ", (1, 2) > ‘foo‘
print "[1, 2] > (1, 2) = ", [1, 2] > (1, 2)


1

2

3

4


print ‘Python‘, python_version()

print "[1, 2] > ‘foo‘ = ", [1, 2] > ‘foo‘

print "(1, 2) > ‘foo‘ = ", (1, 2) > ‘foo‘

print "[1, 2] > (1, 2) = ", [1, 2] > (1, 2)

Python

Python 2.7.6
[1, 2] > ‘foo‘ = False
(1, 2) > ‘foo‘ = True
[1, 2] > (1, 2) = False


1

2

3

4


Python 2.7.6

[1, 2] > ‘foo‘ = False

(1, 2) > ‘foo‘ = True

[1, 2] > (1, 2) = False

Python 3

Python

print(‘Python‘, python_version())
print("[1, 2] > ‘foo‘ = ", [1, 2] > ‘foo‘)
print("(1, 2) > ‘foo‘ = ", (1, 2) > ‘foo‘)
print("[1, 2] > (1, 2) = ", [1, 2] > (1, 2))


1

2

3

4


print(‘Python‘, python_version())

print("[1, 2] > ‘foo‘ = ", [1, 2] > ‘foo‘)

print("(1, 2) > ‘foo‘ = ", (1, 2) > ‘foo‘)

print("[1, 2] > (1, 2) = ", [1, 2] > (1, 2))

Python

Python 3.4.1
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-16-a9031729f4a0> in <module>()
1 print(‘Python‘, python_version())
----> 2 print("[1, 2] > ‘foo‘ = ", [1, 2] > ‘foo‘)
3 print("(1, 2) > ‘foo‘ = ", (1, 2) > ‘foo‘)
4 print("[1, 2] > (1, 2) = ", [1, 2] > (1, 2))
TypeError: unorderable types: list() > str()


1

2

3

4

5

6

7

8

9


Python 3.4.1

---------------------------------------------------------------------------

TypeError Traceback (most recent call last)

<ipython-input-16-a9031729f4a0> in <module>()

1 print(‘Python‘, python_version())

----> 2 print("[1, 2] > ‘foo‘ = ", [1, 2] > ‘foo‘)

3 print("(1, 2) > ‘foo‘ = ", (1, 2) > ‘foo‘)

4 print("[1, 2] > (1, 2) = ", [1, 2] > (1, 2))

TypeError: unorderable types: list() > str()

通过input()解析用户的输入

[回到目录]

幸运的是,Python 3改进了input()函数,这样该函数就会总是将用户的输入存储为str对象。在Python 2中,为了避免读取非字符串类型会发生的一些危险行为,不得不使用raw_input()代替input()。

Python 2

Python

Python 2.7.6
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> my_input = input(‘enter a number: ‘)

enter a number: 123

>>> type(my_input)
<type ‘int‘>

>>> my_input = raw_input(‘enter a number: ‘)

enter a number: 123

>>> type(my_input)
<type ‘str‘>


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17


Python 2.7.6

[GCC 4.0.1 (Apple Inc. build 5493)] on darwin

Type "help", "copyright", "credits" or "license" for more information.

>>> my_input = input(‘enter a number: ‘)

enter a number: 123

>>> type(my_input)

<type ‘int‘>

>>> my_input = raw_input(‘enter a number: ‘)

enter a number: 123

>>> type(my_input)

<type ‘str‘>

Python 3

Python

Python 3.4.1
[GCC 4.2.1 (Apple Inc. build 5577)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> my_input = input(‘enter a number: ‘)
enter a number: 123
>>> type(my_input)
<class ‘str‘>


1

2

3

4

5

6

7

8


Python 3.4.1

[GCC 4.2.1 (Apple Inc. build 5577)] on darwin

Type "help", "copyright", "credits" or "license" for more information.

>>> my_input = input(‘enter a number: ‘)

enter a number: 123

>>> type(my_input)

<class ‘str‘>

返回可迭代对象,而不是列表

[回到目录]

在xrange一节中可以看到,某些函数和方法在Python中返回的是可迭代对象,而不像在Python 2中返回列表。

由于通常对这些对象只遍历一次,所以这种方式会节省很多内存。然而,如果通过生成器来多次迭代这些对象,效率就不高了。

此时我们的确需要列表对象,可以通过list()函数简单的将可迭代对象转成列表。

Python 2

Python

print ‘Python‘, python_version()

print range(3)
print type(range(3))


1

2

3

4


print ‘Python‘, python_version()

print range(3)

print type(range(3))

Python

Python 2.7.6
[0, 1, 2]
<type ‘list‘>


1

2

3


Python 2.7.6

[0, 1, 2]

<type ‘list‘>

Python 3

Python

print(‘Python‘, python_version())
print(range(3))
print(type(range(3)))
print(list(range(3)))


1

2

3

4


print(‘Python‘, python_version())

print(range(3))

print(type(range(3)))

print(list(range(3)))

Python

Python 3.4.1
range(0, 3)
<class ‘range‘>
[0, 1, 2]


1

2

3

4


Python 3.4.1

range(0, 3)

<class ‘range‘>

[0, 1, 2]

下面列出了Python 3中其他不再返回列表的常用函数和方法:

  • zip()
  • map()
  • filter()
  • 字典的.key()方法
  • 字典的.value()方法
  • 字典的.item()方法

更多关于Python 2和Python 3的文章

[回到目录]

下面列出了其他一些可以进一步了解Python 2和Python 3的优秀文章,

//迁移到 Python 3

// 对Python 3的褒与贬

时间: 2024-10-12 15:39:43

Python 2.7.x 和 3.x 版本的重要区别的相关文章

Mcafee两个Mac版本之间的区别

近期打算为Mac安装个杀毒软件,由于自己windows平台下用的是VSE,所以Mac平台也首选Mcafee家的东西了.到Mcafee官网下载点一看,有以下几个版本可以用在Mac上: 有点懵了,查看了一下Endpoint Protection For Mac (以下简称 EPM) 1.2版本是用在10.6.X上的.2.0版本和2.1版本是用在10.7.X.10.8.X.10.9.X上的.而 VirusScan For Mac (以下简称 VSM) 就一个最新版本:9.6再查阅一下两者的区别: 看了

Ubuntu桌面版本和服务器版本之间的区别(转载)

转载自:http://blog.csdn.net/fangaoxin/article/details/6335992 http://www.linuxidc.com/Linux/2010-11/29740.htm 7天免费VPN服务:http://eaesoftvpn.azurewebsites.net/ 说道Linux想必ubuntu的大名大家早就听说,很多都是因为知道ubuntu才知道linux的.但是要提到安装ubuntu那颗就有点犯难了,因为ubuntu的版本太多了,选择哪个安装呢?这确

笨方法学python(6)加分题--列表与字典的区别

he string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIG

win10系统版本之间的区别

调试克隆镜像系统,现有的win10 系统版本之间的区别做一整理如下 win10家庭版: 1.功能简单,满足一般的家庭用户 2.在核心功能,括改进的开始菜单.节电模式.Windows Defender以及Windows防火墙.Cortana语音助手.Windows Hello安全登录.新增的多任务操作,可在传统PC和平板模式之间进行切换的Continuum模式以及Microsoft Edge浏览器等,移动设别管理功能需要等到晚些时候才能到来. win10专业版: 1.非活动窗口鼠标滚动效果这项功能

Oracle一般有哪些版本,各个版本有什么区别呢?

Oracle一般有哪些版本,各个版本有什么区别呢? 专业回答 1977年,Larry Ellison.Bob Miner和Ed Oates等人组建了Relational软件公司(Relational Software Inc.,RSI).他们决定使用C语言和SQL界面构建一个关系数据库管理系统(Relational Database Management System,RDBMS),并很快发布了第一个版本(仅是原型系统). 1979年,RSI首次向客户发布了产品,即第2版.该版本的RDBMS可以

Python 2.7.x 和 3.x 版本区别小结

python现在很火,最近花了些时间去了解了一下,最初了解的是2.7.x版本,感觉,从书写上是很不习惯,少了一双大概号,取而代之的是缩进:然后跟kotlin和swift一样省去了每行的分号,象我们这种分号强迫症的人真心的不习惯:还有!True的条件改成not True.while后面可以跟else等等这些,真心不习惯啊!用2.7.x做了几天的测试,基本慢慢算有个了解了,也试着爬了些行业网的数据,感觉这个比PHP写爬虫方便很多.然后昨晚就在家里装了个3.X的版本,很悲催的发现,原来写的有很多的错误

【Python开发】Python编译器(Pycharm)的安装版本

使用Pycharm作为Python的编译器和调试工具,软件可以从官网下载,下载地址URL为: http://www.jetbrains.com/pycharm/download/#section=windows 版本分为Professional和Community,Professional需要注册,Community为免费版,无需注册,可以直接下载安装! 原文地址:https://www.cnblogs.com/Kevin-WangXinzheng/p/9495195.html

python去除rpm仓库中同名低版本的包

编程思路1 遍历目标路径的rpm包并保存特性包列表: 2 利用python模块rpmUtils提取RPM包的特征信息:包名  版本号 架构 3 遍历特性列表中存在重复包名的rpm, 将低版本的rpm包完整路径信息保存在删除列表中: 4 遍历目标路径,根据删除列表删除低版本的rpm包 函数接口解读: rpmUtils.miscutils.splitFilename  —— https://programtalk.com/python-examples/rpmUtils.miscutils.spli

CentOS 7安装Python 2.6(与已有版本共存)

1. 安装需要用到的包 yum install -y zlib-devel bzip2-devel openssl-devel xz-libs wget 2. 下载 Python 2.6.8 版本 wget https://www.python.org/ftp/python/2.6.8/Python-2.6.8.tgz 3. 解压文件 tar -xzvf Python-2.6.8.tgz 4. 进入解压后文件的目录 cd Python-2.6.8 5. 配置安装信息. ./configure -