__future__ 模塊
Python 3.x引入一些Python2不兼容的關鍵字和函數,可以通過在 Python2 內置的模塊 __future__ 導入。建議如果你想在代碼中支持 Python3.x,使用__future__導入它。
from __future__ import division
print函數
在 Python3 最值得注意和最廣為人知的變化是print函數的使用。print 函數使用的括號()在Python3中是強制性的。它在 Python2 中是可選的。
print "Hello World" #is acceptable in Python 2 print ("Hello World") # in Python 3, print must be followed by ()
print()函數默認情況下在結束時會插入一個換行。在 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 中有輸入函數兩個版本。 input() 和 raw_input()。如果它被包含在引號 '' 或 "",input() 對待接收到的數據作為字符串,否則數據將被視為數字類型。
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,兩個整數的除法的結果會四舍五入到最接近的整數。如:3/2 其結果將顯示 1。 為了獲得一個浮點除法,分子或分母必須明確為浮點數。因此無論是 3.0/2 或 3/2.0 或 3.0/2.0 將產生1.5 。
Python3 中的字符串默認存儲為 Unicode。在Python3,我們有個Unicode(UTF-8)字符串和 2 字節類:字節和字節數組。
在Python3,range()函數去除了,而 xrange()已更名為 range()。 另外在 Python3.2 以及更高的版本中, range()對象支持切片。
Python2 中同時接受符號的'大膽'和'新'的語法;如果我們不在括號中括入異常參數,Python3 中會引發一個 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
next() 函數和.next()方法
在Python 2,next() 作為生成器對象的一個方法是允許的。在 Python2,next()函數過度產生器對象遍歷也是可以接受的。在Python3,但是,next()函數作為生成器方法來中止並引發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
2to3實用工具
隨着 Python3 解釋器,2t03.py 腳本將被通常安裝在 tools/scripts 文件夾。 它讀取 Python2.x 源代碼,並應用了一系列的修復將它轉變成有效的 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)