Summary of differences between Python2 and Python3

Source: Internet
Author: User
Tags deprecated integer division

I. Basic grammatical differences 1.1 core class differences
    1. Python3 native support for Unicode characters

      The use of ASCII code as the default encoding in Python2 causes string to have two types of STR and unicode,python3 that support only Unicode strings. The Python2 and Python3 bytes and characters correspond to the following relationships:

    2. The Python3 uses an absolute path to import.

      Import of relative paths in Python2 can make standard library imports difficult (imagine that there are file.py in the same directory, how to import both this file and the standard library files). This will be modified in Python3, and if you need to import files for the same directory, you must use an absolute path, otherwise you can only import using the relevant import.

    3. There are differences between the old class and the new class in the Python2, Python3 unifies the new class. New class declarations require inheriting object, and multiple inheritance must be applied with modern classes.

    4. The Python3 uses more stringent indentation. In the Python2 indentation mechanism, 1 tab and 8 space are equivalent, so you can allow both tab and space to coexist in the code in the indentation. This equivalence mechanism causes problems with some IDE usage. Python3 1 tabs can only find another tab override, so tab and space coexistence will result in an error: Taberror:inconsistent use of tabs and spaces in indentation.

1.2 Waste class Differences
  1. Print statements are Python3 discarded, using the print () function uniformly

  2. EXEC statements are python3 deprecated, using the EXEC () function uniformly

  3. ExecFile statement is deprecated by Python3, it is recommended to use EXEC (open ("./filename"). Read ())

  4. Inequality operator "<>" is deprecated by Python3 and uses "! =" uniformly

  5. Long Integer type is Python3 deprecated and uses int uniformly

  6. The xrange function is Python3 discarded, and the mechanism of using range in Range,python3 is modified and the efficiency of large data set generation is improved.

  7. These methods in Python3 no longer return a list object: Dictionary associated keys (), values (), items (), zip (), map (), filter (), but can be forcibly converted by list :

    Mydict={"A": 1, "B": 2, "C": 3}mydict.keys ()  #<built-in method Keys of Dict object at 0x000000000040b4c8>list ( Mydict.keys ()) #[' A ', ' C ', ' B ']
  8. The next () function of the iterator iterator is discarded by Python3, using next (iterator) uniformly

  9. raw_input function is discarded by Python3, using the input function uniformly

  10. The has_key function of the dictionary variable is discarded by Python, using the In keyword uniformly

  11. The file function is discarded by Python3, using open to work with files, which can be done via IO. Iobase Checking file types

  12. The apply function is Python3 discarded

  13. Abnormal standarderror is Python3 discarded, unified use exception

1.3 Modifying class differences
  1. Floating-point Division Operator/and//Difference

    • python2:/is integer division,//IS fractional division
    • python3:/is a fractional division,//is an integer division.
  2. Exception throwing and snapping mechanism differences

    • Python2
    Raise IOError, "File Error" #抛出异常except Nameerror, err:  #捕捉异常
    • Python3
    Raise IOError("File Error") as err: #捕捉异常
  3. Variable value difference in for loop

    • Python2,for loop modifies the value of the external same name variable
    i = 1print (' comprehension: ', [i-I in range (5)]) print (' after:i = ', I  ) #i =4
    • Python3,for Loop does not modify the value of the external same name variable
    i = 1print (' comprehension: ', [i-I in range (5)]) print (' after:i = ', I  
  4. Round function return value difference

    • The Python2,round function returns a value of type float
     
      
    • The Python3,round function returns an int type value
  5. comparison operator Differences

    • Any two objects in a Python2 can be compared
     
      
    • Only objects of the same data type in Python3 can be compared
    < ' test ' # typeerror:unorderable Types:int () < STR ()
1.4 New Class Differences

All new features added in python3.x are not supported in Python2, and descriptions of these new features are detailed in the official website:

    • 3.1 https://docs.python.org/3.1/whatsnew/
    • 3.2 https://docs.python.org/3.2/whatsnew/3.2.html
    • 3.3 https://docs.python.org/3.3/whatsnew/3.0.html
    • 3.4 https://docs.python.org/3.4/whatsnew/3.4.html
    • 3.5 https://docs.python.org/3.5/whatsnew/3.5.html
    • 3.6 https://docs.python.org/3.6/whatsnew/3.6.html

There is a blog post on the important points of these features in China, which can be used as a reference: http://www.cnblogs.com/animalize/p/5633215.html

Second, third-party tool kits

We are in pip official download source PyPI The number of third-party toolkit searches for Python2.7 and Python3.5 can be found, the number of third-party tools that correspond to the Python2.7 version is 28523, The number of Python3.5 versions is 12457, and the two versions in the third-party toolkit support a significant gap.

https://pypi.python.org/pypi?:action=browse&c=532

https://pypi.python.org/pypi?:action=browse&c=607

2.1 Module Merging

Stringio and Cstringio in Python2 are merged into IO in Python3

The pickle and Cpickle in Python2 are merged into Pickle in Python3.

Urllib, Urllib2, and Urlparse in Python2 are merged Python3 in Urllib

2.2 Renaming a module

Python3 Python2
Configparser Configparser
Filter Itertools.ifilter
Input Raw_input
Map Itertools.imap
Range Xrange
Functools.reduce Reduce
Socketserver Socketserver
Zip Itertools.izip

2.3 Data Analysis Toolkit

We have enumerated common and useful third-party toolkits (the following table) from the point of view of the application of data analysis, and analyzed the support of these toolkits in Python2.7 and Python3.5:

category Tool Name Use
Data collection Scrapy Web Capture, crawler
Data collection Scrapy-redis Distributed crawler
Data collection Selenium Web testing, emulation browser
Data processing BeautifulSoup Web page Interpretation Library, providing lxml support
Data processing lxml XML Interpretation Library
Data processing Xlrd Excel file Read
Data processing Xlwt Excel file Write
Data processing Xlutils Simple format modification of Excel file
Data processing Pywin32 Read-write and complex format customization for Excel files
Data processing Python-docx Read Write to Word file
Data analysis NumPy Matrix-based Mathematical computing library
Data analysis Pandas Table-based statistical analysis library
Data analysis SciPy Scientific Computing Library to support higher-order abstractions and complex models
Data analysis Statsmodels Statistical Modelling and Econometrics Toolkit
Data analysis Scikit-learn Machine Learning Tool Library
Data analysis Gensim Natural Language Processing Tool Library
Data analysis Jieba Chinese Word breaker tool Gallery
Data storage Mysql-python MySQL read-write interface library
Data storage Mysqlclient MySQL read-write interface library
Data storage SQLAlchemy ORM Encapsulation of databases
Data storage Pymssql SQL Server read-write interface library
Data storage Redis Redis read-write interface
Data storage Pymongo MongoDB read-write interface
Data rendering Matplotlib Popular Data Visualization Library
Data rendering Seaborn Beautiful data Visualization library, based on Matplotlib
Tool Assist Jupyter Web-based Python IDE, often used for data analysis
Tool Assist Chardet Character Check tool
Tool Assist Configparser Configuration file read/write support
Tool Assist Requests HTTP Libraries for network access
2.4 Tool Installation Issues
    • Windows environment

Python2 cannot install mysqlclient. Python3 cannot install Mysql-python, Flup, functools32, gooey, Pywin32, webencodings.

Matplotlib installation Error in PYTHON3 environment: The following required packages can not be built:freetype, PNG. Need to manually download Install Source package installation solution.

Scrapy install error in Python3 environment, install VC++2015 installation package: Http://landinghub.visualstudio.com/visual-cpp-build-tools

SCIPY installation Error in Python3 environment, Numpy.distutils.system_info. Notfounderror, you need to manually download the corresponding installation package, rely on Numpy,pandas must be strictly based on the Python version, operating system, 64-bit or not.

Run Matplotlib after the discovery of the basic Package NUMPY+MKL installation failed, need to download, domestic no download source

    • In the CentOS environment

Python2 Unable to install Mysql-python and mysqlclient package, error: Environmenterror:mysql_config not found, the solution is to install Mysql-devel package solution. Use Matplotlib Error: No module named _tkinter, install Tkinter, tk-devel, Tc-devel solve.

Pywin32 also cannot be installed in the CentOS environment.

2.5 Tool Test Results

After addressing the installation issues described above, a simple case of running the toolkit was written in the test script (appendix), and the test results were passed, indicating that the third-party toolkit installed successfully in both Windows and the CentOS environment.

Resources:

Https://www.cnblogs.com/kendrick/p/7478304.html

78983725

Summary of differences between Python2 and Python3

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.