Python future use

Each new version of Python adds some new functionality or makes some changes to the original functionality. Some changes are not compatible with the old version, that is, the code that runs normally in the current version may not run normally in the next version.

There are some incompatible changes from Python 2.7 to Python 3.x. For example, strings in 2.x are used to 'xxx'represent str, and Unicode strings are used to u'xxx'represent unicode. In 3.x, all strings are treated as unicode. , therefore, the writing u'xxx'sum 'xxx'is exactly the same, and in 2.x, 'xxx'the str represented by it must be written b'xxx'as "binary string".

Upgrading the code directly to 3.x is rather aggressive, because there are a lot of changes to test. On the contrary, you can test some 3.x features in a part of the code in the 2.7 version, and if there is no problem, it will be no later than porting to 3.x.

Python provides __future__modules to import the features of the next new version into the current version, so we can test some new version features in the current version. An example is as follows:

There is a division operation. In Python 2.x, there are two cases for division. If it is an integer division, the result is still an integer, and the remainder will be thrown away. This division is called "floor division":

>>> 10 / 3
3

To do exact division, you must convert one of the numbers to a floating point number:

>>> 10.0 / 3
3.3333333333333335

In Python 3.x, all divisions are exact divisions, and floor division is //represented by:

$ python3
Python 3.3.2 (default, Jan 22 2014, 09:54:40) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> 10 / 3 3.3333333333333335 >>> 10 // 3 3 

If you want to use Python 3.x division directly in Python 2.7 code, you can implement it through __future__the module division:

from __future__ import division

print '10 / 3 =', 10 / 3 print '10.0 / 3 =', 10.0 / 3 print '10 // 3 =', 10 // 3

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325884089&siteId=291194637