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.python

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中的除法有两个运算符,/和//cookie

首先来讲/除法:
在python 2.x中/除法就跟咱们熟悉的大多数语言,好比Java啊C啊差很少,整数相除的结果是一个整数,把小数部分彻底忽略掉,浮点数除法会保留小数点的部分获得一个浮点数的结果。less

在python 3.x中/除法再也不这么作了,对于整数之间的相除,结果也会是浮点数。socket

Python 2.x:ide

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

0.5而对于//除法,这种除法叫作floor除法,会对除法的结果自动进行一个floor操做,在python 2.x和python 3.x中是一致的。oop

python 2.x:ui

-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)
0this

异常

在 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替代它吧 。

相关文章
相关标签/搜索