Python2.x difference with version 3 .x
3.0 versions of Python, often referred to as Python 3000, or simply Py3k. With respect to an earlier version of Python, this is a major upgrade.
In order not to bring too much burden, Python 3.0 does not consider in the design of downward compatibility.
For many programs designed earlier versions of Python will not perform properly on Python 3.0.
In order to take care of the existing program, Python 2.6 as an interim version of the Python 2.x using the basic syntax and libraries, taking into account the migration to Python 3.0 and Python 3.0 allows the use of part of the syntax of the function.The new program is recommended to use Python 3.0 Python version syntax.
Unless the execution environment can not install Python 3.0 or the program itself does not support the use of third-party libraries Python 3.0. Currently does not support third-party libraries Python 3.0 are Twisted, py2exe, PIL and the like.
Most third-party libraries are trying to Python 3.0 compatible version. If not immediately use Python 3.0, also recommended the development of compatible Python 3.0 version of the program, and then use Python 2.6, Python 2.7 is performed.
Changes in Python 3.0 is mainly in the following areas:
print statement is gone, replaced by a print () function. Python 2.6 and Python 2.7 support in part this form of print syntax. In Python 2.6 and Python 2.7 inside, three forms are equivalent:
print "fish" print ("fish") #注意print后面有个空格 print("fish") #print()不能带有任何其它参数
However, Python 2.6 has actually support the new print () syntax:
from __future__ import print_function print("fish", "panda", sep=', ')
Python 2 had ASCII str () type, unicode () alone, not byte type.
Now, in Python 3, we finally have Unicode (utf-8) string and a byte class: byte and bytearrays.
Because Python3.X source file default utf-8 encoding, which makes the following code is legal:
>>> 中国 = 'china' >>>print(中国) china
>>> 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'
>>> str = "我爱北京天安门" >>> str '我爱北京天安门'
Python division in other languages than the very high end, there is a very complex set of rules. Python in the division with two operators, and / //
First, it / Division:
In the python 2.x / division just like most of us are familiar with the language, such as Java ah ah C is similar to the results of an integer division was an integer, the fractional part is completely ignored, decimal floating point division will remain a part of the get results floating-point number.
In the python 3.x / division no longer do so, and for the division between integers, the result will be a float.
>>> 1 / 2 0 >>> 1.0 / 2.0 0.5
>>> 1/2 0.5
For // division, this division is called floor division, the result will division automatically a floor operation is the same in python 2.x and python 3.x in.
>>> -1 // 2 -1
>>> -1 // 2 -1
Note that not discard the fractional part, but to carry on the operation floor, if you want to intercept the fractional part, you need to use math function module trunc
>>> import math >>> math.trunc(1 / 2) 0 >>> math.trunc(-1 / 2) 0
Processing in Python 3 is also slightly abnormal changes, in Python 3, we now use as a keyword.
Syntax for catching exceptions madeexcept exc, var changed except exc as var.
Syntax except (exc1, exc2) as var can catch exceptions multiple categories. Python 2.6 has support for both syntax.
- 1. 2.x era, are all types of objects that can be thrown directly in the 3.x era, only inherited from BaseException objects can be thrown.
- 2. 2.x raise statement throws a comma to separate object types and parameters, 3.x canceled this wonderful wording directly call the constructor throws an object can be.
In 2.x era, anomalies in the code in addition to that procedural errors, but also often do some common control structures should do, in 3.x can be seen, the designers make a more specific abnormal change only in error with the exception of the case in order to catch statement to handle.
Create iteration object in Python 2 in xrange () usage is very popular. For example: for loop or a list / collection / dictionary comprehensions.
This performance is very image generator (eg. "Lazy evaluation"). But the xrange-iterable is infinite, unlimited means that you can traverse.
Because of its lazy evaluation, not only if you can not traverse it once, xrange () function ratio range () faster (eg for cycles). Nevertheless, compared to one iteration, iteration is not recommended that you repeat several times, because the generator from scratch each time.
In Python 3, range () is like xrange () so as to achieve a specific xrange () function no longer exists (In Python 3 xrange () will throw an exception name).
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
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 loop
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 loop
print(xrange(10)) --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-5-5d8f9b79ea70> in <module>() ----> 1 print(xrange(10)) NameError: name 'xrange' is not defined
Octal literal representation
Octal number must be written 0o777, the original form of 0777 can not be used; must be written in binary 0b111.
Added a bin () function is used to convert an integer into a binary string. Python 2.6 has support for both syntax.
In Python 3.x, and octal literal only one way, that is 0o1000.
>>> 0o1000 512 >>> 01000 512
>>> 01000 File "<stdin>", line 1 01000 ^ SyntaxError: invalid token >>> 0o1000 512
Python 2.x does not mean there are two ways for writing! = And <>
Python 3.x to drop the <> Only! = Way to write, but fortunately, I never use <> diet
Removed the expression `` repr
Python 2.x in back quotes `` repr function is equivalent to the role of
Python 3.x to drop the `` notation, allowed only repr function, purpose of doing so is to make the code looks more clear it? But I feel with the opportunity to repr rarely, usually only when it is used in debug, most of the time or use the str function to a string describing the object.
def sendMail(from_: str, to: str, title: str, body: str) -> bool: pass
A plurality of modules are renamed (according PEP8)
|The old name||New name|
StringIO module is now incorporated into the new io module. new, md5, gopherlib modules are deleted. Python 2.6 has support for the new io module.
httplib, BaseHTTPServer, CGIHTTPServer, SimpleHTTPServer, Cookie, cookielib be incorporated into the http package.
Cancel the exec statement, only the exec () function. Python 2.6 has support exec () function.
5. Data Types
1) Py3.X removed long type, now there is only one integer --int, but it behaves like a 2.X version of the long
2) Added bytes type corresponding to the 2.X version of the eight series, define a bytes literal method is as follows:
>>> b = b'china' >>> type(b) <type 'bytes'>
str objects and bytes objects can use .encode () (str -> bytes) or .decode () (bytes -> str) method into each other.
>>> s = b.decode() >>> s 'china' >>> b1 = s.encode() >>> b1 b'china'
3) dict of .keys () ,. items and .values () method returns an iterator, whereas the previous iterkeys () and other functions are discarded. At the same time removed there dict.has_key (), replace it with in it.