1. 程式人生 > >python2和python3主要區別

python2和python3主要區別

這篇文章主要介紹了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的整數除法行為,可以通過下面的語句匯入相應的模組。

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

示例:

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

1 2 3 4 print 'Python', python_version() print 'Hello, World!' print('Hello, World!') print "text", ; print '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

1 2 3 4 5 print('Python', python_version()) print('Hello, World!') print("some text,", end="") print(' 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
1 print 'Hello, World!'
File "<ipython-input-3-139a7c5835bd>", line 1 print 'Hello, World!' ^ SyntaxError: invalid syntax

注意:

在Python中,帶不帶括號輸出”Hello World”都很正常。但如果在圓括號中同時輸出多個物件時,就會建立一個元組,這是因為在Python 2中,print是一個語句,而不是函式呼叫。

1 2 3 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

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 2.7.6
3 / 2 = 1
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0

Python 3

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 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

1 print 'Python', python_version()
Python 2.7.6
1 print type(unicode('this is like a python3 str type'))
<type 'unicode'>
1 print type(b'byte type does not exist')
<type 'str'>
1 print 'they are really' + b' the same'
they are really the same
1 print type(bytearray(b'bytearray oddly does exist though'))
<type 'bytearray'>

Python 3

1 2 print('Python', python_version()) print('strings are now utf-8 u03BCnicou0394é!')
Python 3.4.1
strings are now utf-8 μnicoΔé!
1 2 print('Python', python_version(), end="") print(' has', type(b' bytes for storing data'))
Python 3.4.1 has <class 'bytes'>
1 2 print('and Python', python_version(), end="") print(' also has', type(bytearray(b'bytearrays')))
and Python 3.4.1 also has <class 'bytearray'>
?
1 '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)。

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

?
1 2 3 4 5 6 7 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

?
1 2 3 4 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
?
1 print(xrange(10))
---------------------------------------------------------------------------
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中整數和布林型的“查詢”速度。

?
1 2 3 4 5 6 7 8 9 10 11 12 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 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中的整數和浮點數的查詢速度差別不大。

?
1 2 3 4 5 6 7 8 9 10 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 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__方法:

?
1 2 print('Python', python_version()) range.__contains__
Python 3.4.1
<slot wrapper '__contains__' of 'range' objects
?
1 2 print('Python', python_version()) range.__contains__
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 print('Python', python_version()) xrange.__contains__
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慢。

?
1 2 3 4 5 def test_while():  i = 0  while i < 20000:   i += 1  return
?
1 2 print('Python', python_version()) %timeit test_while()
Python 3.4.1
%timeit test_while()
100 loops, best of 3: 2.68 ms per loop
?
1 2 print 'Python', python_version() %timeit test_while()
Python 2.7.6
1000 loops, best of 3: 1.72 ms per loop

觸發異常

Python 2支援新舊兩種異常觸發語法,而Python 3只接受帶括號的的語法(不然會觸發SyntaxError):

Python 2

1 print 'Python', python_version()
Python 2.7.6
1 raise IOError, "file error"
---------------------------------------------------------------------------
IOError Traceback (most recent call last)
<ipython-input-8-25f049caebb0> in <module>()
----> 1 raise IOError, "file error"
 
IOError: file error
1 raise IOError("file error")
---------------------------------------------------------------------------
IOError Traceback (most recent call last)
<ipython-input-9-6f1c43f525b2> in <module>()
----> 1 raise IOError("file error")
 
IOError: file error

Python 3

1 print('Python', python_version())
Python 3.4.1
1 raise IOError, "file error"
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 print('Python', python_version()) raise IOError("file error")
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

1 2 3 4 5 print 'Python', python_version() try:  let_us_cause_a_NameError except NameError, err:  print err, '--> our error message'
Python 2.7.6
name 'let_us_cause_a_NameError' is not defined --> our error message

Python 3

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 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

1 2 3 4 print 'Python', python_version() my_generator = (letter for letter in 'abcdefg') next(my_generator) my_generator.next()
Python 2.7.6
'b'

Python 3

1 2 3 print('Python', python_version()) my_generator = (letter for letter in 'abcdefg') next(my_generator)
Python 3.4.1
'a'
?
1 my_generator.next()
---------------------------------------------------------------------------
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

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 2.7.6
before: i = 1
comprehension: [0, 1, 2, 3, 4]
after: i = 4

Python 3

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 3.4.1
before: i = 1
comprehension: [0, 1, 2, 3, 4]
after: i = 1

比較無序型別

Python 3中另一個優秀的改動是,如果我們試圖比較無序型別,會觸發一個TypeError。

Python 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 2.7.6
[1, 2] > 'foo' = False
(1, 2) > 'foo' = True
[1, 2] > (1, 2) = False

Python 3

?
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 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

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

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

1 2 3 4 print 'Python', python_version() print range(3) print type(range(3))
Python 2.7.6
[0, 1, 2]
<type 'list'>

Python 3

1 2 3 4 print('Python', python_version()) print(range(3)) print(type(range(3))) print(list(range(3)))
Python 3.4.1
range(0, 3)
<class 'range'>
[0, 1, 2]

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

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

相關推薦

python2python3主要區別

這篇文章主要介紹了Python 2.7.x 和 3.x 版本的重要區別小結,需要的朋友可以參考下 許多Python初學者都會問:我應該學習哪個版本的Python。對於這個問題,我的回答通常是“先選擇一個最適合你的Python教程,教程中使用哪個版本的Python,你就用那

python2python3區別?

ima tps python3 cnblogs .cn alt mage log http python2和python3的區別?

urllib庫python2python3具體區別

ble log redirect proxy dmgr python3 button ner net Python 2 name Python 3 name urllib.urlretrieve() urllib.request.urlretrieve(

Python2Python3區別

rexec args ring 獲得 mapping decorator 整型 import true 17年入手Python語言,直接學的是Python3的語法,後來出去面試發現幾乎所有招Python後端開發的都會問到Python2和Python3的區別,而且說得越詳細則

python2python3編碼區別

str TE python2 clas python 文件 分別是 兩個 ’b’ 在python2中主要有str和unicode兩種字符串類型,而到python3中改為了bytes和str,並且一個很重要的分別是,在python2中如果字符串是ascii碼的話,s

python2python3區別 (附帶程式碼解析)

1. input()函式 python2中的input()函式:獲取當前輸入的內容,並將其作為指令來處理 ; python3中的input()函式:獲取當前輸入的內容,並將其作為字串來處理; 在pytohn2環境中: 在輸入中文‘小花’的時候,會顯示語法

python2python3區別之inpuraw_input的區別

python2:input和raw_input的區別,raw_input會把輸入的任何內容都當做字串來處理, 剛開始做if判斷的時候,a和b都是整數,沒有問題,後面a是通過raw_input接收的,就不能比較了,a是str,b是int python3已經廢棄raw_input input

python2python3區別表格版

區別點 python2 python3 print 是一個語法結構,print 'hello world',print("hello world")都可以 是一個函式,print("hello

python2python3區別(不斷更新)

目前百度回答或網上的教程使用Python2.x的比較多,但直接copy程式碼會顯示錯誤;故將遇見的python3.x的改動總結一下: 更新日期:2018.3.23 一到2018年12月31日為止,所有的NumPy版本都將完全支援Python2和Python

python的輸入輸出——python2python3主要區別

一、python的輸入輸出: 程式的輸入輸出流程: 輸入(鍵盤) ————程式碼(java/python/c)————輸出(螢幕) 變數的定義: 在python中。每個變數在使用之前都必須賦值,變數賦值後該變數才會被建立。 等號(=)就算用來給變數賦值的。

第一個python程式——python2python3使用的主要區別

python2 和python3的主要區別: 編碼格式 python2中有兩種字串型別:Unicode字串和非Unicode字串。 Python3中只有一種型別:Unicode字串。 python2編碼格式:ASCII碼 python3編碼格式:unicode碼 2.

python2python3主要區別

作為一個py3土著,並不是很關心這個稀碎的問題,但是總有人隔三差五問這個問題,還是捋了一下。 這裡列出幾個主要區別: 1、最常見的人盡皆知的print()函式 在py2中,print是一個語句,不帶括號,也可以帶括號。 在py3中,print是一個函式,必須帶括號呼叫。 2、除法 # Python

Python2 Python3主要區別

Python2和Python3中的主要區別 Python2 和 Python3的區別體現在如下幾個方面: 1. print的改變 2. 編碼的改變 3. True和False的改變 4. nonlocal關鍵字 5. 迭代器的改變 1

Python2Python3的一些語法區別

pythonPython2和Python3的一些語法區別pythonPython2和Python3的一些語法區別1.print2.input3. python3版本相對2版本的部分其他區別問題:為何會出現亂碼的情況問題:如何獲取編碼方式的信息?問題:在控制臺上看到的到底是什麽?1.print在版本2的使用方法

python2 python3 區別

col clas () requests restfu .get python .json style python2 python 2 必須加object加入後是新式類 python 2 不加object是經典類 class HTTP(object): # 經典

淺談Python2Python3區別

1.首先編碼;   Python2 :   (1).預設編碼是ASCII碼型別,如果發現其他編碼非ASCII編碼是通常會報錯 UnicodeDecodeError: 'ascii' codec can't decode byte 0x?? in position 1: ordinal not in ran

【python】第一日 python2python3區別 命名方式 三種結構

一、python2和python3區別 1)print 語句區別   python2:print是個class,所以可以不用加括號,print 1,2+3   python3:print是個內建函式,必須加括號,print(1,2+3,end=" ") 2)input區別   python2:inp

python2python3中整數相除的區別

       今天初次接觸python,學習的是python2,我的編譯器是python3,所以在學除法的時候,自己實驗的結果和教材結果不一致。 所以就查了一下,原來,python3做了優化,整數相除的結果可以為小數,比如10/4的結果就為2.5而不是py

Python2Python3區別:input

python2.x 在python2.x中raw_input( )和input( ),兩個函式都存在 其中區別為 raw_input( )---將所有輸入作為字串看待,返回字串型別 inpu

python2python3區別

1.效能  Py3.0執行 pystone benchmark的速度比Py2.5慢30%。Guido認為Py3.0有極大的優化空間,在字串和整形操作上可  以取得很好的優化結果。  Py3.1效能比Py2.5慢15%,還有很大的提升空間。 2.編碼 Py3.X原始碼檔