Python 3.x引入一些Python2不兼容的關(guān)鍵字和函數(shù),可以通過在 Python2 內(nèi)置的模塊 __future__ 導(dǎo)入。建議如果你想在代碼中支持 Python3.x,使用__future__導(dǎo)入它。
from __future__ import division
在 Python3 最值得注意和最廣為人知的變化是print函數(shù)的使用。print 函數(shù)使用的括號()在Python3中是強(qiáng)制性的。它在 Python2 中是可選的。
print "Hello World" #is acceptable in Python 2
print ("Hello World") # in Python 3, print must be followed by ()
print()函數(shù)默認(rèn)情況下在結(jié)束時會插入一個換行。在 Python2,它可以通過 ',' 在末行抑制輸出換行。 在 Python3 則使用"end=' '" 附加空格,而不是換行
print x, # Trailing comma suppresses newline in Python 2 print(x, end=" ") # Appends a space instead of a newline in Python 3
Python2 中有輸入函數(shù)兩個版本。 input() 和 raw_input()。如果它被包含在引號 '' 或 "",input() 對待接收到的數(shù)據(jù)作為字符串,否則數(shù)據(jù)將被視為數(shù)字類型。
In Python 2 >>> x=input('something:')
something:10 #entered data is treated as number
>>> x
10
>>> x=input('something:')
something:'10' #eentered data is treated as string
>>> x
'10'
>>> x=raw_input("something:")
something:10 #entered data is treated as string even without ''
>>> x
'10'
>>> x=raw_input("something:")
something:'10' #entered data treated as string including ''
>>> x
"'10'" In Python 3 >>> x=input("something:")
something:10
>>> x
'10'
>>> x=input("something:")
something:'10' #entered data treated as string with or without ''
>>> x
"'10'"
>>> x=raw_input("something:") # will result NameError
Traceback (most recent call last):
File "", line 1, in x=raw_input("something:")
NameError: name 'raw_input' is not defined
在Python2,兩個整數(shù)的除法的結(jié)果會四舍五入到最接近的整數(shù)。如:3/2 其結(jié)果將顯示 1。 為了獲得一個浮點除法,分子或分母必須明確為浮點數(shù)。因此無論是 3.0/2 或 3/2.0 或 3.0/2.0 將產(chǎn)生1.5 。
Python3 中的字符串默認(rèn)存儲為 Unicode。在Python3,我們有個Unicode(UTF-8)字符串和 2 字節(jié)類:字節(jié)和字節(jié)數(shù)組。
在Python3,range()函數(shù)去除了,而 xrange()已更名為 range()。 另外在 Python3.2 以及更高的版本中, range()對象支持切片。
Python2 中同時接受符號的'大膽'和'新'的語法;如果我們不在括號中括入異常參數(shù),Python3 中會引發(fā)一個 SyntaxError:
raise IOError, "file error" #This is accepted in Python 2
raise IOError("file error") #This is also accepted in Python 2
raise IOError, "file error" #syntax error is raised in Python 3
raise IOError("file error") #this is the recommended syntax in Python 3
except Myerror, err: # In Python2 except Myerror as err: #In Python 3
在Python 2,next() 作為生成器對象的一個方法是允許的。在 Python2,next()函數(shù)過度產(chǎn)生器對象遍歷也是可以接受的。在Python3,但是,next()函數(shù)作為生成器方法來中止并引發(fā)AttributeError。
gen = (letter for letter in 'Hello World') # creates generator object next(my_generator) #allowed in Python 2 and Python 3 my_generator.next() #allowed in Python 2. raises AttributeError in Python 3
隨著 Python3 解釋器,2t03.py 腳本將被通常安裝在 tools/scripts 文件夾。 它讀取 Python2.x 源代碼,并應(yīng)用了一系列的修復(fù)將它轉(zhuǎn)變成有效的 Python3.x 代碼。
Here is a sample Python 2 code (area.py):
def area(x,y=3.14):
a=y*x*x
print a
return a
a=area(10)
print "area",a
To convert into Python 3 version:
$2to3 -w area.py
Converted code :
def area(x,y=3.14): # formal parameters
a=y*x*x
print (a)
return a
a=area(10)
print("area",a)