Python2 与 Python3 区别
Python2.x 與 Python3.x 區別
1. print 函數
Python2 中 print 是語句(statement),Python3 中 print 則變成了函數。在 Python3 中調用print 需要加上括號,不加括號會報 SyntaxError。Python2 中使用逗號 , 表示不換行;
Python3 中使用 print (“hi”,end="") 使用 end="" 表示不換行;
2. 整數相除
在Python2 中,3/2 的結果是整數,在 Python3 中,結果則是浮點數。
3. 編碼方式
Python2 中的默認編碼是 ASSCII,至于是為什么會使用 asscii 作為默認編碼,原因在于 Python 2 出來的時候還沒出現 Unicode。Python3 默認采用了 UTF-8 作為默認編碼,因此你不再需要在文件頂部寫 # coding=utf-8 了。
4. 字符串
Python2 有兩種字符串類型:str 和 unicode,Python3 中的字符串默認就是 Unicode,Python3 中的 str 相當于Python2 中的 unicode。
5. 異常處理
Python2.x 中捕獲異常一般用下面的語法:
try:1/0
except ZeroDivisionError, e:print str(e)
或者
try:1/0
except ZeroDivisionError as e:print str(e)
Python3 中不再支持前一種語法,必須使用 as 關鍵字。
6. 內置函數
-
xrange
Python2 中有 range 和 xrange 兩個方法。其區別在于,range 返回一個 list,在被調用的時候即返回整個序列;xrange 返回一個 iterator,在每次循環中生成序列的下一個數字。Python3 中不再支持 xrange 方法,Python3 中的 range 方法就相當于 Python2 中的 xrange 方法。
-
高階函數
Python2中 zip(), map() 和 filter() 直接返回列表;
Python3 中 zip(), map() 和 filter() 直接返回迭代器,如果要變列表,必須要加 list;
-
字典
Python3 中:字典里面 dict.keys(), dict.items() 和 dict.values() 方法返回迭代器,去掉了 Python2里面的 iterkeys(),去掉的 dict.has_key(),Python3 中用 in 替代它。
7. 賦值變量
Python2 中 a,b,*res=[1,2,3,4] 這樣寫是會報錯的,但是 Python3 里面寫就合法。
8. 類的繼承
Python2 里面子類繼承父類經常要寫 super 這個函數,就是子類初始的話要記得初始化父類,這時 super() 里面要填一些參數。
class Parent(object):def __init__(self):self.a = 100class Child(Parent):def __init__(self):super(Child, self).__init__()c = Child()
print c.a
Python3 里面直接簡化了這個過程,省掉 super() 里面的參數,更簡潔更 Pythonic。
class Parent(object):def __init__(self):self.a = 100class Child(Parent):def __init__(self):super().__init__()c = Child()
print c.a
9. 語法方面
- 關鍵詞加入 as 和 with,還有 True, False, None
- 加入 nonlocal 語句。使用 noclocal x 可以直接指派外圍(非全局)變量
- 同樣的還有 exec 語句,已經改為 exec() 函數
- 輸入函數改變了,刪除了 raw_input,用 input 代替
- 擴展的可迭代解包。在 Python3 里,a, b, *rest = seq 和 *rest, a = seq 都是合法的,只要求兩點:rest是list
- 迭代器的next()方法改名為__next__(),并增加內置函數next(),用以調用迭代器的__next__()方法
10. 數據類型
新增了 bytes 類型,對應于 Python2 版本的八位串,定義一個 bytes 字面量的方法如下:
>>> b = b'china'
>>> type(b)
<type 'bytes'>
str 對象和 bytes 對象可以使用 .encode() (str -> bytes) or .decode() (bytes -> str)方法相互轉化。
>>> s = b.decode() >>> s 'china' >>> b1 = s.encode() >>> b1 b'china'
11. True 和 False
True 和 False 在 Python2 中是兩個全局變量(名字),在數值上分別對應 1 和 0。Python3 修正了這個缺陷,True 和 False 變為兩個關鍵字,永遠指向兩個固定的對象,不允許再被重新賦值。
12. 待補充
擴展鏈接
http://python.jobbole.com/89031/
總結
以上是生活随笔為你收集整理的Python2 与 Python3 区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python 常用内置函数map、zip
- 下一篇: Python 典型错误及关键知识点