python2和python3的區別

2021-09-26 10:13:20 字數 2361 閱讀 2193

python3介紹的一些python2不相容的關鍵字和特性可以通過在python2的內建__future__模組匯入,如果在python2中支援python3的**,可以匯入__future__模組。

python2:

print 'python',python_version()

print 'hello world'

print 'name is',;print 'gallo'

#result:

#python 2.7.6

#hello world

#name is gallo

python3:
print('python',python_version())

print('hello world')

print("name is",end="")

print("gallo")

#reslut:

#python 3.7.1

#hello world

#name is gallo

python3的版本變化中,整數計算可以說是很大的並且可能在移植過程中造成很大的危險。

python2

>>> 3/2

>>> 3//2

>>> 3/2.0

>>> 3

#result

# 1# 1

# 1.5

# 1.0

python3
>>> 3/2

>>> 3//2

>>> 3/2.0

>>> 3

# reslut

# 1.5

# 1

# 1.5

# 1.0

python 2中ascll 是字串型別,unicode()是單獨的,不是byte型別

現在,在python3有了unicode(utf-8)字串,以及乙個位元組類:byte和bytearrays型別。

由於python3原始碼檔案預設使用utf-8編碼,使得變數名為漢字合法。

>>>梅西 = 『messi』

>>>print(梅西)

messi

python2
>>>str = '梅西'

>>>str

'\xe6\x88\x91\xe7\x88\xb1\xe5\x8c'

python3
>>> str = "我喜歡踢足球"

>>> str

'我喜歡踢足球'

將捕獲異常的方法從 except exc,var 改為 except exc as var.

python 2中不等於有兩種寫法 !=和<>

python 3中去掉了<>,只有!=一種寫法

python 2中反引號 `` 相當於repr函式的作用.

python 3只允許使用repr函式.

**repr()**將物件轉化為供直譯器讀取的形式。

在python3中當不可排序型別作比較的時候,會丟擲乙個型別錯誤。

python 2

>>> [1,2] > 'foo'

>>>(1,2) > 'foo'

>>>[1,2] > (1,2)

#result

#false

#true

#false

python 3
[1,2] > 'foo'

(1,2)>'foo'

[1,2]>(1,2)

#將會報錯 :不同資料型別之間不能進行比較

python2方法與函式都可以使用,在python3中使用.next()方法會丟擲異常。

在python3中input的型別都為字串型別,但是在python2中如果輸入123將預設為int型別,如果要保證輸入的為字串型別應該使用的是raw_input()

python 2

>>> my_input = input('enter a number:')

enter a number: 123

>>> type(my_input)

>>> my_input = raw_input('enter a number:')

enter a number: 123

>>> type(my_input)

#只有input()函式

my_input = input('enter a number')

enter a number: 123

type(my_input)

python3和python2的區別

1.效能 py3.0執行 pystone benchmark的速度比py2.5慢30 guido認為py3.0有極大的優化空間,在字串和整形操作上可 以取得很好的優化結果。py3.1效能比py2.5慢15 還有很大的提公升空間。2.編碼 py3.x原始碼檔案預設使用utf 8編碼,這就使得以下 是合...

Python2和Python3的比較

python2 python3 print fish print fish unicode 是單獨的 unicode utf 8 字串 b b china byte 和 bytearrays type b type bytes s b.decode 轉化成 string 型別b1 s encode ...

python3和python2的區別

這個星期開始學習python了,因為看的書都是基於python2.x,而且我安裝的是python3.1,所以書上寫的地方好多都不適用於python3.1,特意在google上search了一下3.x和2.x的區別。特此在自己的空間中記錄一下,以備以後查詢方便,也可以分享給想學習python的frie...