The difference Python3 and Python2

table of Contents

print

  • Python2.7 is not a function of print
  • Python3 where the print is a function.

Unicode

  • Python 2 had ASCII str () type, Unicode () alone, instead of a byte type.
  • Python 3, we finally have Unicode (utf-8) string, as well as a class byte: byte and bytearrays.

Because Python3.X source file using the default utf-8 encoding, which makes the following code is legal:

>>> 中国 = '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
'我爱北京天安门'

Division

Python in the division than other languages ​​is very high, there is a very complex set of rules. Python division in two operators, / and //

First of all / division:

In the python 2.x / division just as we are familiar with most languages, such as Java C ah ah almost integer result of the division is an integer, the fractional part is completely ignored, decimal floating-point division will remain part of getting a the results of floating point numbers.

In the python 3.x / division did not, for the division between integers, floating point result will be.

Python 2.x:

>>> 1 / 2
0
>>> 1.0 / 2.0
0.5

Python 3.x:

>>> 1/2
0.5

For // division, this division is called a division floor, a floor operation will automatically result of division, it is the same in the python 2.x and python 3.x.

python 2.x:

>>> -1 // 2
-1

python 3.x:

>>> -1 // 2
-1

Note that not discarding the decimal portion, but the implementation of floor operations, if you want to intercept integer part, you need to use the math module function trunc

python 3.x:

>>> import math
>>> math.trunc(1 / 2)
0
>>> math.trunc(-1 / 2)
0

abnormal

3 abnormal processing in Python also slightly changed, and we now use as a keyword in Python 3.
Syntax for catching exceptions made except exc, var changed except exc as var.
Syntax except (exc1, exc2) as var can catch exceptions multiple categories at the same time. Python 2.6 has support for both syntax.

  1. In 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 uses commas to separate thrown object types and parameters, 3.x canceled the wording of this wonderful work directly call the constructor throws an object can be.

In 2.x era, anomalies in the code in addition to that program errors, but also often do some things common control structures should do, it can be seen in 3.x, the designers make an exception become more loyal, and only in error the situation in order to deal with abnormal capture statement.

xrange

Creating an iteration object in Python xrange 2 () usage is extremely popular. For example: for a loop or list / set / inferential dictionary.

The performance is like a generator (such as. "Lazy evaluation"). But this xrange-iterable is infinite, unlimited means that you can traverse.

Because of its lazy evaluation, if you have to traverse it several times, xrange () function () faster (for example for loop) ratio range. Nevertheless, a comparison of 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 in 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   

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 loop

Python 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 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; binary must be written 0b111.

Added a bin () function is used to convert an integer to a binary string. Python 2.6 has support for both syntax.

In Python 3.x, the octal literal only one way, that is 0o1000.

python 2.x

>>> 0o1000
512
>>> 01000
512

python 3.x

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

Inequality operators

Python 2.x is not written in two equal! = And <>

Python 3.x removed in <> Only! = Way to write, but fortunately, I never use <> habits

Removed repr expression Python 2.x 中反引号acts as repr function

Python 3.x removed in `` The wording, only allows the use repr function, purpose of doing so is to make the code look more clear it? But I feel a little chance repr, generally only used when debug, and most of the time or use string str function to describe 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
_winreg winreg
ConfigParser configparser
copy_reg copyreg
Queue queue
SocketServer socketserver
repr Repro

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 http is incorporated into the package.

Canceled the exec statement, only the exec () function. Python 2.6 has support exec () function.

type of data

  1. Py3.X removed long type, now there is only one integer --int, but it behaves like a 2.X version of the long, because we ostensibly an int actually PyLongObject in CPython source code, so, in fact Py3.x removed int type, only the long type.

  2. New types of bytes corresponding to eight strings version 2.X, a definition of the literal bytes as follows:

>>> b = b'china' 
>>> type(b) 
<type 'bytes'> 

str bytes objects and objects may be used .encode () (str -> bytes) or .decode () (bytes -> str) interconversion methods.

>>> s = b.decode() 
>>> s 
'china' 
>>> b1 = s.encode() 
>>> b1 
b'china' 
  1. dict the .keys () ,. items and .values ​​() method returns an iterator, but before the iterkeys () function and the like are discarded. Meanwhile removed as well dict.has_key (), replace it with in it.

Guess you like

Origin www.cnblogs.com/daryl-blog/p/11003070.html
Recommended