基於python3淺談python3與python2的差別。因爲現今主流Python3,可是以前用Python2作的項目,還得維護,因此做爲python工做者,難免要了解其中差別,其中,Python2 有 ASCII str() 類型,unicode() 是單獨的,不是 byte 類型。而 Python3.X 源碼文件默認使用utf-8編碼,以及一個字節類:byte 和 bytearrays。這就使得如下代碼是合法的: python
編碼差別: markdown
我 = 'zhongguo' 函數
print(我)ui
Python3結果:zhongguo編碼
注:python2中是不合法的,不管是代碼仍是註釋都是不能出現漢字的,除非申明:#!/usr/bin/python -*- coding: UTF-8 -*-spa
做爲一種默認規範或者代碼素養,一般不用漢字,儘可能讓代碼寫的python點! .net
python3與python2最大的區別就是print輸出,請參考print的使用:https://blog.csdn.net/u010986753code
Python 3版本中print語句沒有了,取而代之的是print()函數。orm
print差別:對象
正確輸出"life is short we neeed python!"代碼以下:
print('life is short we neeed python!')
Python3結果:life is short we neeed python!
Python2中的打印:
print "life is short we neeed python!"/
print 'life is short we neeed python!'/
print ('life is short we neeed python!')
輸出結果都是同樣的!
整除差別
> print(7/3)>
Python3結果:2.3333333333333335
> Python2結果:2
> Python3表示整除是print(7//3)
不等號的差別:
Python2中不等於有兩種寫法 != 和 <>
Python3中去掉了<>, 只有!=一種寫法
整型的差別:
Python2中有一種整型—int和長整型-long
Python3中只有一種整型—int
提示信息的差別:
Python2中raw_input( "提示信息" )和input( "提示信息" )
Python3中只有input( "提示信息" )
打開文件的差別:
Python2中file( ..... )或 open(.....)
Python3中只有open(.....)
map、filter 和 reduce的差別:
Python2在交互模式下:
>>> map
<built-in function map>
>>> filter<built-in function filter>
>>> reduce<built-in function reduce>
它們輸出的結果類型都是列表:
>>> map(lambda x:x +2, [4,1,3])
[6, 3, 5]
>>> filter(lambda x:x %2 ==0,range(9))
[0, 2, 4, 6, 8]
Python3在交互模式下:它們從函數變成了類,其次,它們的返回結果也從當初的列表成了一個可迭代的對象
>>> map<class 'map'>
>>> map(print,[1,2,3])
<map object at 0x10d8bd400>
>>> filter<class 'filter'>
>>> filter(lambda x:x % 2 == 0, range(10))
<filter object at 0x10d8bd3c8>
遍歷元組
對於比較高端的 reduce 函數,它在 Python3中已經不屬於 built-in 了,被挪到 functools 模塊當中。若是須要編寫一個遍歷元組的列表解析,Python2不須要在元組值周圍加上括號。在python3裏,這些括號是必需的。
Python2中[ i for i in 1, 2]
Python3中[i for i in (1,2)]
得到必定範圍內的數字
python2裏,有兩種方法得到必定範圍內的數字:range(),返回一個列表,還有xrange(),返回一個迭代器。
python3 裏,range()返回迭代器,xrange()再也不存在。
Python2中[ i for i in 1, 2]
Python3中[i for i in (1,2)]
歡迎關注小婷兒的博客 https://blog.csdn.net/u010986753不足之處請留言,會盡快修改!