Python 2.7.x 和 3.x 版本的重要区别(1)
Python 2.7.x 和 3.x 版本的重要区别(1)
许多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的整数除法行为,可以通过下面的语句导入相应的模块。
- 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)
示例:
- 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
- print 'Python', python_version()
- print 'Hello, World!'
- print('Hello, World!')
- print "text", ; print 'print more text on the same line'
- Python 2.7.6
- Hello, World!
- Hello, World!
- text print more text on the same line
Python 3
- print('Python', python_version())
- print('Hello, World!')
- print("some text,", end="")
- print(' print more text on the same line')
- Python 3.4.1
- Hello, World!
- some text, print more text on the same line
- print 'Hello, World!'
- File "<ipython-input-3-139a7c5835bd>", line 1
- print 'Hello, World!'
- ^
- SyntaxError: invalid syntax
注意:
在Python中,带不带括号输出”Hello World”都很正常。但如果在圆括号中同时输出多个对象时,就会创建一个元组,这是因为在Python 2中,print是一个语句,而不是函数调用。
- print 'Python', python_version()
- print('a', 'b')
- print 'a', 'b'
- 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
- 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 2.7.6
- 3 / 2 = 1
- 3 // 2 = 1
- 3 / 2.0 = 1.5
- 3 // 2.0 = 1.0
Python 3
- 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 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中,终于有了Unicodeutf-8)字符串,以及两个字节类:bytes和bytearrays。
Python 2
- print 'Python', python_version()
- Python 2.7.6
- print type(unicode('this is like a python3 str type'))
- <type 'unicode'>
- print type(b'byte type does not exist')
- <type 'str'>
- print 'they are really' + b' the same'
- they are really the same
- print type(bytearray(b'bytearray oddly does exist though'))
- <type 'bytearray'>
Python 3
- print('Python', python_version())
- print('strings are now utf-8 u03BCnicou0394é!')
- Python 3.4.1
- strings are now utf-8 μnicoΔé!
- print('Python', python_version(), end="")
- print(' has', type(b' bytes for storing data'))
- Python 3.4.1 has <class 'bytes'>
- print('and Python', python_version(), end="")
- print(' also has', type(bytearray(b'bytearrays')))
- and Python 3.4.1 also has <class 'bytearray'>
- 'note that we cannot add a string' + b'bytes for data'
- ---------------------------------------------------------------------------
- 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)。
- 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
- print 'Python', python_version()
- print 'ntiming range()'
- %timeit test_range(n)
- print 'nntiming xrange()'
- %timeit test_xrange(n)
- 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
- print('Python', python_version())
- print('ntiming range()')
- %timeit test_range(n)
- Python 3.4.1
- timing range()
- 1000 loops, best of 3: 520 µs per loop
- print(xrange(10))
- ---------------------------------------------------------------------------
- NameError Traceback (most recent call last)
- in ()
- ----> 1 print(xrange(10))
- NameError: name 'xrange' is not defined
评论关闭