python3和Python2的區別(被坑太久了)


print函數:(Python3中print為一個函數,必須用括號括起來;Python2中print為class)

Python 2 的 print 聲明已經被 print() 函數取代了,這意味着我們必須包裝我們想打印在小括號中的對象。

Python 2

1
2
3
4
print 'Python', python_version()
print 'Hello, World!'
print( 'Hello, World!')
print "text", ; print 'print more text on the same line'

run result:
Python 2.7.6
Hello, World!
Hello, World!
text print more text on the same line

Python 3

1
2
3
4
print( 'Python', python_version())
print( 'Hello, World!')
print( "some text,", end="")
print( ' print more text on the same line')

run result:
Python 3.4.1
Hello, World!
some text, print more text on the same line


通過input()解析用戶的輸入:(Python3中input得到的為str;Python2的input的到的為int型,Python2的raw_input得到的為str類型)統一一下:Python3中用input,Python2中用row_input,都輸入為str

幸運的是,在 Python 3 中已經解決了把用戶的輸入存儲為一個 str 對象的問題。為了避免在 Python 2 中的讀取非字符串類型的危險行為,我們不得不使用 raw_input() 代替。

Python 2
Python 2.7.6
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type “help”, “copyright”, “credits” or “license” for more information.

>>> my_input = input('enter a number: ')  enter a number: 123 >>> type(my_input) <type 'int'> >>> my_input = raw_input('enter a number: ')  enter a number: 123 >>> type(my_input) <type 'str'> 

Python 3
Python 3.4.1
[GCC 4.2.1 (Apple Inc. build 5577)] on darwin
Type “help”, “copyright”, “credits” or “license” for more information.

>>> my_input = input('enter a number: ')  enter a number: 123 >>> type(my_input) <class 'str'>

 


 

整除:(沒有太大影響)(Python3中/表示真除,%表示取余,//表示地板除(結果取整);Python2中/表示根據除數被除數小數點位得到結果,//同樣表示地板除)統一一下:Python3中/表示真除,%表示取余,//結果取整;Python2中帶上小數點/表示真除,%表示取余,//結果取整

Python 2

1
2
3
4
5
print 'Python', python_version()
print '3 / 2 =', 3 / 2
print '3 // 2 =', 3 // 2
print '3 / 2.0 =', 3 / 2.0
print '3 // 2.0 =', 3 // 2.0

run result:
Python 2.7.6
3 / 2 = 1
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0

Python 3

1
2
3
4
5
print( 'Python', python_version())
print( '3 / 2 =', 3 / 2)
print( '3 // 2 =', 3 // 2)
print( '3 / 2.0 =', 3 / 2.0)
print( '3 // 2.0 =', 3 // 2.0)

run result:
Python 3.4.1
3 / 2 = 1.5
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0


 

xrange模塊:

在 Python 3 中,range() 是像 xrange() 那樣實現以至於一個專門的 xrange() 函數都不再存在(在 Python 3 中xrange() 會拋出命名異常)。

在 Python 2 中 xrange() 創建迭代對象的用法是非常流行的。比如: for 循環或者是列表/集合/字典推導式。
  這個表現十分像生成器(比如。“惰性求值”)。但是這個 xrange-iterable 是無窮的,意味着你可以無限遍歷。
  由於它的惰性求值,如果你不得僅僅不遍歷它一次,xrange() 函數 比 range() 更快(比如 for 循環)。盡管如此,對比迭代一次,不建議你重復迭代多次,因為生成器每次都從頭開始。


 

 

 

 

 

 

 

 

待補充。。。

http://chenqx.github.io/2014/11/10/Key-differences-between-Python-2-7-x-and-Python-3-x/

http://www.cnblogs.com/codingmylife/archive/2010/06/06/1752807.html



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 語句的變化

原: try:

          ......

     except    Exception, e :

         ......

改為

    try:

          ......

     except    Exception as e :

         ......

五、打開文件

原: 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("?")

 

 

RookieDong的補充

1,“import  thread”問題,2.x中的模塊thread在3.x中編程"_thread"(需要在前面加一個下划線).否則會出現“ImportError: No module named thread



 

 

 

 

 

dd


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM