當前位置:編程學習大全網 - 編程語言 - python3.4學習筆記 3.x和2.x的區別,持續更新

python3.4學習筆記 3.x和2.x的區別,持續更新

python3.4學習筆記(四) 3.x和2.x的區別

在2.x中:print html,3.x中必須改成:print(html)

import urllib2

ImportError: No module named 'urllib2'

在python3.x裏面,用urllib.request代替urllib2

import thread

ImportError: No module named 'thread'

在python3.x裏面,用_thread(在前面加壹個下劃線)代替thread

在2.x中except Exception,e : 3.x中改為except (Exception):

=================================

print函數

雖然print語法是Python 3中壹個很小的改動,且應該已經廣為人知,但依然值得提壹下:Python 2中的print語句被Python 3中的print()函數取代,這意味著在Python 3中必須用括號將需要輸出的對象括起來。

在Python 2中使用額外的括號也是可以的。但反過來在Python 3中想以Python2的形式不帶括號調用print函數時,會觸發SyntaxError。

Python 2.7.6

print 'Python', python_version()

print 'Hello, World!'

print('Hello, World!')

print "text", ; print 'print more text on the same line'

輸出:

Hello, World!

Hello, World!

text print more text on the same line

---------------------------

Python 3.4.1

print('Python', python_version())

print('Hello, World!')

print("some text,", end="")

print(' print more text on the same line')

輸出:

Hello, World!

some text, print more text on the same line

print 'Hello, World!'

File "<ipython-input-3-139a7c5835bd>", line 1

print 'Hello, World!'

^

SyntaxError: invalid syntax

註意:在Python中,帶不帶括號輸出”Hello World”都很正常。

但如果在圓括號中同時輸出多個對象時,就會創建壹個元組,這是因為在Python 2中,print是壹個語句,而不是函數調用。

print 'Python', python_version()

print('a', 'b')

print 'a', 'b'

Python 2.7.7

('a', 'b')

a b

---------------------------------

整數除法

由於人們常常會忽視Python 3在整數除法上的改動(寫錯了也不會觸發Syntax Error),所以在移植代碼或在Python 2中執行Python 3的代碼時,需要特別註意這個改動。

所以,我還是會在Python 3的腳本中嘗試用float(3)/2或 3/2.0代替3/2,以此來避免代碼在Python

2環境下可能導致的錯誤(或與之相反,在Python 2腳本中用from __future__ import division來使用Python

3的除法)。

Python 2.7.6

3 / 2 = 1

3 // 2 = 1

3 / 2.0 = 1.5

3 // 2.0 = 1.0

Python 3.4.1

3 / 2 = 1.5

3 // 2 = 1

3 / 2.0 = 1.5

3 // 2.0 = 1.0

---------------------------------

Unicode

Python 2有基於ASCII的str()類型,其可通過單獨的unicode()函數轉成unicode類型,但沒有byte類型。

而在Python 3中,終於有了Unicode(utf-8)字符串,以及兩個字節類:bytes和bytearrays。

Python 2.7.6

print type(unicode('this is like a python3 str type'))

<type 'unicode'>

print type(b'byte type does not exist')

<type 'str'>

print 'they are really' + b' the same'

they are really the same

print type(bytearray(b'bytearray oddly does exist though'))

<type 'bytearray'>

Python 3.4.1 has <class 'bytes'>

print('and Python', python_version(), end="")

print(' also has', type(bytearray(b'bytearrays')))

and Python 3.4.1 also has <class 'bytearray'>

1

'note that we cannot add a string' + b'bytes for data'

---------------------------------------------------------------------------

TypeError Traceback (most recent call last)

<ipython-input-13-d3e8942ccf81> in <module>()

----> 1 'note that we cannot add a string' + b'bytes for data'

TypeError: Can't convert 'bytes' object to str implicitly

=================================

python 2.4 與 python 3.0 的比較

壹、 print 從語句變為函數

原: print 1,2+3

改為: print ( 1,2+3 )

二、range 與 xrange

原 : range( 0, 4 ) 結果 是 列表 [0,1,2,3 ]

改為:list( range(0,4) )

原 : xrange( 0, 4 ) 適用於 for 循環的變量控制

改為:range(0,4)

三、字符串

原: 字符串以 8-bit 字符串存儲

改為: 字符串以 16-bit Unicode 字符串存儲

四、try except 語句的變化

在2.x中except Exception,e : 3.x中改為except (Exception):

五、打開文件

原: file( ..... )

或 open(.....)

改為:

只能用 open(.....)

六、從鍵盤錄入壹個字符串

原: raw_input( "提示信息" )

改為: input( "提示信息" )

七、bytes 數據類型

A bytes object is an immutable array. The items are 8-bit bytes, represented by integers in the range 0 <= x < 256.

bytes 可以看成是“字節數組”對象,每個元素是 8-bit 的字節,取值範圍 0~255。

由於在 python 3.0中字符串以 unicode 編碼存儲,當寫入二進制文件時,字符串無法直接寫入(或讀取),必須以某種方式的編碼為字節序列後,方可寫入。

(壹)字符串編碼(encode) 為 bytes

例: s = "張三abc12"

b = s.encode( 編碼方式)

# b 就是 bytes 類型的數據

# 常用的編碼方式為 : "uft-16" , "utf-8", "gbk", "gb2312", "ascii" , "latin1" 等

# 註 : 當字符串不能編碼為指定的“編碼方式”時,會引發異常

(二) bytes 解碼(decode)為字符串

s = "張三abc12"

b = s.encode( "gbk") # 字符串 s 編碼為 gbk 格式的字節序列

s1 = b.decode("gbk") # 將字節序列 b以gbk格式 解碼為字符串

# 說明,當字節序列不能以指定的編碼格式解碼時會引發異常

(三)使用方法舉例

#coding=gbk

f = open("c:\\1234.txt", "wb")

s = "張三李四abcd1234"

# -------------------------------

# 在 python2.4 中我們可以這樣寫:

# f.write( s )

# 但在 python 3.0中會引發異常

# -------------------------------

b = s.encode("gbk")

f.write( b )

f.close()

input("?")

讀取該文件的例子:

#coding=gbk

f = open("c:\\1234.txt", "rb")

f.seek(0,2) #定位至文件尾

n = f.tell() #讀取文件的字節數

f.seek(0,0) #重新定位至文件開始處

b = f.read( n )

# ------------------------------

# 在 python 2.4 中 b 是字符串類型

# 要 python 3.0 中 b 是 bytes 類型

# 因此需要按指定的編碼方式確碼

# ------------------------------

s = b.decode("gbk")

print ( s )

# ------------------------------

# 在 python 2.4 中 可以寫作 print s 或 print ( s )

# 要 python 3.0 中 必須寫作 print ( s )

# ------------------------------

f.close()

input("?")

運行後應顯示:

張三李四abcd1234

(四) bytes序列,壹但形成,其內容是不可變的,例:

s="ABCD"

b=s.encode("gbk")

print b[0] # 顯示 65

b[0] = 66

# 執行該句,出現異常: 'bytes' object does not support item assignment

八、 chr( K ) 與 ord( c )

python 2.4.2以前

chr( K ) 將編碼K 轉為字符,K的範圍是 0 ~ 255

ord( c ) 取單個字符的編碼, 返回值的範圍: 0 ~ 255

python 3.0

chr( K ) 將編碼K 轉為字符,K的範圍是 0 ~ 65535

ord( c ) 取單個字符的編碼, 返回值的範圍: 0 ~ 65535

九、 除法運算符

python 2.4.2以前

10/3 結果為 3

python 3.0

10 / 3 結果為 3.3333333333333335

10 // 3 結果為 3

十、字節數組對象 --- 新增

(壹) 初始化

a = bytearray( 10 )

# a 是壹個由十個字節組成的數組,其每個元素是壹個字節,類型借用 int

# 此時,每個元素初始值為 0

(二) 字節數組 是可變的

a = bytearray( 10 )

a[0] = 25

# 可以用賦值語句更改其元素,但所賦的值必須在 0 ~ 255 之間

(三) 字節數組的切片仍是字節數組

(四) 字符串轉化為字節數組

#coding=gbk

s ="妳好"

b = s.encode( "gbk") # 先將字符串按某種“GBK”編碼方式轉化為 bytes

c = bytearray( b ) #再將 bytes 轉化為 字節數組

也可以寫作

c = bytearray( "妳好", "gbk")

(五) 字節數組轉化為字符串

c = bytearray( 4 )

c[0] = 65 ; c[1]=66; c[2]= 67; c[3]= 68

s = c.decode( "gbk" )

print ( s )

# 應顯示: ABCD

(六) 字節數組可用於寫入文本文件

#coding=gbk

f = open("c:\\1234.txt", "wb")

s = "張三李四abcd1234"

# -------------------------------

# 在 python2.4 中我們可以這樣寫:

# f.write( s )

# 但在 python 3.0中會引發異常

# -------------------------------

b = s.encode("gbk")

f.write( b )

c=bytearray( "王五","gbk")

f.write( c )

f.close()

input("?")

  • 上一篇:妳在哪個瞬間覺得數學是美的,或者被震撼到?
  • 下一篇:C語言的編程問題,求高手解答啊。新手很不明白。6月19號之前需要用到。急急急!!!我把財富全部給妳。。
  • copyright 2024編程學習大全網