python2和python3的區別

官方維基:

https://wiki.python.org/moin/Python2orPython3

引用官方一段話:

What are the differences?
Short version: Python 2.x is legacy, Python 3.x is the present and future of the language
Python 3.0 was released in 2008. The final 2.x version 2.7 release came out in mid-2010, with a statement of extended support for this end-of-life release. The 2.x branch will see no new major releases after that. 3.x is under active development and has already seen over five years of stable releases, including version 3.3 in 2012, 3.4 in 2014, and 3.5 in 2015. This means that all recent standard library improvements, for example, are only available by default in Python 3.x.
Guido van Rossum (the original creator of the Python language) decided to clean up Python 2.x properly, with less regard for backwards compatibility than is the case for new releases in the 2.x range. The most drastic improvement is the better Unicode support (with all text strings being Unicode by default) as well as saner bytes/Unicode separation.
Besides, several aspects of the core language (such as print and exec being statements, integers using floor division) have been adjusted to be easier for newcomers to learn and to be more consistent with the rest of the language, and old cruft has been removed (for example, all classes are now new-style, "range()" returns a memory efficient iterable, not a list as in 2.x).
The What's New in Python 3.0 document provides a good overview of the major language changes and likely sources of incompatibility with existing Python 2.x code. Nick Coghlan (one of the CPython core developers) has also created a relatively extensive FAQ regarding the transition.
However, the broader Python ecosystem has amassed a significant amount of quality software over the years. The downside of breaking backwards compatibility in 3.x is that some of that software (especially in-house software in companies) still doesn't work on 3.x yet.

Python2.x與3.x版本區別

Python的3.0版本,常被稱爲Python3000或簡稱Py3k,相對於Python的早期版本,這是一個較大升級。
爲了不帶入過多的累贅,Python 3.0在設計的時候沒有考慮向下相容。許多針對早期Python版本設計的程式都無法在Python 3.0上正常執行。
爲了照顧現有程序,Python2.7作爲一個過渡版本,基本使用了Python2.x的語法和庫,同時考慮了向Python3.0的遷移,允許使用部分Python3.0的語法與函數。
新的Python程序建議使用Python 3.0的語法。除非執行環境無法安裝Python 3.0或者程序本身使用了不支持Python 3.0的第三方庫。目前不支持Python 3.0的第三方庫有Twisted, py2exe, PIL等。大多數第三方庫都正在努力地兼容Python 3.0。即使無法立即使用Python 3.0,也建議編寫兼容Python 3.0版本的程序,然後使用Python2.6或2.7來執行。

Python 3.0的變化主要在以下幾個方面:

print 函數

print語句沒有了,取而代之的是print()函數。 Python 2.6與2.7部分地支持這種形式的print語法。在Python 2.6與2.7裏面,以下兩種形式是等價的:
print "fish"
print ("fish")

print("fish")不能帶有任何其它參數然而,Python 2.6實際已經支持新的print()語法:
from __future__ import print_function
print("fish", "panda", sep=', ')

Unicode

Python 2 有 ASCII str() 類型,unicode() 是單獨的,不是 byte 類型。
現在,Python 3最終有了 Unicode (utf-8) 字符串,以及一個字節類:byte 和 bytearrays。

由於 Python3.X 源碼文件默認使用utf-8編碼,這就使得以下代碼是合法的:
>>> 中國 = 'china' 
>>> print(中國) 
china

Python 2.x
>>> str = "我愛北京天安門"
>>> str
'\xe6\x88\x91\xe7\x88\xb1\xe5\x8c\x97\xe4\xba\xac\xe5\xa4\xa9\xe5\xae\x89\xe9
\x97\xa8'
>>> str = u"我愛北京天安門"
>>> str
u'\u6211\u7231\u5317\u4eac\u5929\u5b89\u95e8'Python 3.x
>>> str = "我愛北京天安門"
>>> str
'我愛北京天安門'

除法運算

Python中的除法較其它語言顯得非常高端,有套很複雜的規則。Python中的除法有兩個運算符,/和//

首先來說/除法:
在python 2.x中/除法就跟我們熟悉的大多數語言,比如Java啊C啊差不多,整數相除的結果是一個整數,把小數部分完全忽略掉,浮點數除法會保留小數點的部分得到一個浮點數的結果。

在python 3.x中/除法不再這麼做了,對於整數之間的相除,結果也會是浮點數。

Python 2.x:

>> 1 / 2
0
>> 1.0 / 2.0
0.5
Python 3.x:
>> 1/2

0.5而對於//除法,這種除法叫做floor除法,會對除法的結果自動進行一個floor操作,在python 2.x和python 3.x中是一致的。

python 2.x:

>> -1 // 2
-1
python 3.x:
>> -1 // 2
-1
注意:並不是捨棄小數部分,而是執行floor操作,如果要截取小數部分,那麼需要使用math模塊的trunc函數
python 3.x:
>> import math
>> math.trunc(1 / 2)
0
>> math.trunc(-1 / 2)
0

異常

在 Python 3 中處理異常也輕微的改變了,在 Python 3 中我們現在使用 as 作爲關鍵詞。
捕獲異常的語法由 except exc, var 改爲 except exc as var。
使用語法except (exc1, exc2) as var可以同時捕獲多種類別的異常。
Python 2.6已經支持這兩種語法。

  1. 在2.x時代,所有類型的對象都是可以被直接拋出的,在3.x時代,只有繼承自BaseException的對象纔可以被拋出。
  2. 2.x raise語句使用逗號將拋出對象類型和參數分開,3.x取消了這種奇葩的寫法,直接調用構造函數拋出對象即可。
    在2.x時代,異常在代碼中除了表示程序錯誤,還經常做一些普通控制結構應該做的事情,在3.x中可以看出,設計者讓異常變的更加專一,只有在錯誤發生的情況才能去用異常捕獲語句來處理。

xrange

在 Python 2 中 xrange() 創建迭代對象的用法是非常流行的。比如: for 循環或者是列表/集合/字典推導式。
這個表現十分像生成器(比如。"惰性求值")。但是這個 xrange-iterable 是無窮的,意味着你可以無限遍歷。
由於它的惰性求值,如果你不得僅僅不遍歷它一次,xrange() 函數 比 range() 更快(比如 for 循環)。儘管如此,對比迭代一次,不建議你重複迭代多次,因爲生成器每次都從頭開始。
在 Python 3 中,range() 是像 xrange() 那樣實現以至於一個專門的 xrange() 函數都不再存在(在 Python 3 中 xrange() 會拋出命名異常)。

   import timeit

    n = 10000
    def test_range(n):
        return for i in range(n):
            pass

    def test_xrange(n):
        for i in xrange(n):
            pass   Python 2
    print 'Python', python_version()

    print '\ntiming range()' 
    %timeit test_range(n)

    print '\n\ntiming xrange()' 
    %timeit test_xrange(n)

    Python 2.7.6

    timing range()
    1000 loops, best of 3: 433 µs per loop

    timing xrange()
    1000 loops, best of 3: 350 µs per loopPython 3
    print('Python', python_version())

    print('\ntiming range()')
    %timeit test_range(n)

    Python 3.4.1

    timing range()
    1000 loops, best of 3: 520 µs per loopprint(xrange(10))
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-5-5d8f9b79ea70> in <module>()
    ----> 1 print(xrange(10))

    NameError: name 'xrange' is not defined

八進制字面量表示

八進制數必須寫成0o777,原來的形式0777不能用了;二進制必須寫成0b111。
新增了一個bin()函數用於將一個整數轉換成二進制字串。 Python 2.6已經支持這兩種語法。
在Python 3.x中,表示八進制字面量的方式只有一種,就是0o1000。
python 2.x

>> 0o1000
512
>> 01000
512python 3.x
>> 01000
File "<stdin>", line 1
01000
^
SyntaxError: invalid token
>> 0o1000
512

不等運算符

Python 2.x中不等於有兩種寫法 != 和 <>
Python 3.x中去掉了<>, 只有!=一種寫法,還好,我從來沒有使用<>的習慣

去掉了repr表達式``

Python 2.x 中反引號相當於repr函數的作用<br/>Python 3.x 中去掉了這種寫法,只允許使用repr函數,這樣做的目的是爲了使代碼看上去更清晰麼?不過我感覺用repr的機會很少,一般只在debug的時候才用,多數時候還是用str函數來用字符串描述對象。

    def sendMail(from_: str, to: str, title: str, body: str) -> bool:
        pass

多個模塊被改名(根據PEP8)

| 舊的名字 | 新的名字 |
| _winreg | winreg |
| ConfigParser | configparser |
| copy_reg | copyreg |
| Queue | queue |
| SocketServer | socketserver |
| repr | reprlib |

StringIO模塊現在被合併到新的io模組內。 new, md5, gopherlib等模塊被刪除。 Python 2.6已經支援新的io模組。
httplib, BaseHTTPServer, CGIHTTPServer, SimpleHTTPServer, Cookie, cookielib被合併到http包內。
取消了exec語句,只剩下exec()函數。 Python 2.6已經支援exec()函數。

數據類型
1)Py3.X去除了long類型,現在只有一種整型int,但它的行爲就像2.X版本的long
2)新增了bytes類型,對應於2.X版本的八位串,定義一個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'
3)dict的.keys()、.items 和.values()方法返回迭代器,而之前的iterkeys()等函數都被廢棄。同時去掉的還有 dict.has_key(),用 in替代它吧 。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章