What are the main differences between Python 2 and Python 3?

Source: Internet
Author: User
Tags integer division


Reply content:


Let me correct and comment.
> 1. Print is no longer a statement, but a function, such as the original print ' ABC ' is now print (' abc ')
However, python2.6+ can use the from __future__ import print_function to achieve the same functionality
> 2. In Python 3, there is no old-fashioned class, only the new class, which means no more like this class Foobar (object): Pass explicitly sub-class object
But it's better to add it. The main difference is that Old-style is a ClassType type and New-style is type
> 3. Turns out 1/2 (two integers) The result is 0, and now it's 0.5.
Python 2.2+ above can be modified using the From __FUTURE__ Import division, while note//replace the previous/operation
> 4. New string formatting method format supersedes%
Error, the method has been found in STR and Unicode starting from python2.6+, while Python3 still supports the% operator
> 6. Xrange Rename to Range
There are also a series of built-in functions and methods that return iterator objects, not lists or tuples, such as filter, map, Dict.items, etc.
> 7. ! = Supersedes < >
Python2 rarely used < > so it's not much of a change.
> 8. Long is renamed INT
Not exactly, Python3. The method of Long+int double integer implementation, unified as int, supports high precision integer operation.
> 9. Except Exception, E becomes except (Exception) as E
This syntax is not supported for python2.5 and the following versions only. The python2.6 is supported. It's not new.
> 10. exec becomes a function
A change like print (), preceded by a statement.

Simply add the following
* Mainly the change of class library, the organizational structure has changed a little. But the function has not changed. Urlparse-> Urllib.parse such a change
* Most core changes it does not say that support for bytes and native Unicode strings, the deletion of Unicode objects, str as native Unicode strings, bytes instead of the previous STR This is the most core.
* Other ... It doesn't seem very important. I have to add a very important thing to see that everyone has not said:
Import is imported by default with absolute path in Python3, because the import of relative paths is ambiguous
such as folder structure:
    • test/
      • main.py
      • lib/
        • __init__.py
        • some_func.py
        • other_func.py
If you are running a main.py file, Python will use the current CWD as the Pythonpath variable
In main.py, the
Import Lib.some_func
Or
From
Lib import some_func
In some_func.py, if the use of import Other_func will be an error, it is recommended to use
From
Lib import other_func
Forced use of relative imports requires from. Other_func Import *
So, migrating from Python2 to Python3, you will see a large project with the original code structure is good, if your code is everywhere relative import ... Gee
See also: PEP 0328--Imports:multi-line and Absolute/relative

Detailed 2to3 Migration considerations can refer to the documentation for the 2TO3 library: 26.6.2to3-automated Python 2 to 3 code translation The parts that can be migrated automatically don't have to be artificial. The main difference between ~python 2.7.x and Python 3.x , details the differences between Python 2 and Python 3, and put some good articles in it to help you. The main differences between Python 2.7.x and Python 3.x
    • Using the __future__ module
    • Print function
    • Integer Division
    • Unicode
    • Xrange
    • Raising exceptions
    • Handling Exceptions
    • Next () function and the. Next () method
    • For loop variables and global namespace leaks
    • Compare non-sortable types
    • Parsing the user's input via input ()
    • Returns an iterative object instead of a list

The original address is
Key differences between Python 2.7.x and Python 3.x

Translated address is
The main differences between Python 2.7.x and Python 3.x The main difference between the changes is Python3 program can be written in Chinese

However, it is funny that some people say that it is not very good to read Chinese writing procedures (the exact words).

I think he meant to be less accustomed, but still very funny. Wondering if he feels accustomed to looking in the mirror every day.

If there is such a sick company/boss, then there is no way to take short hands. PY3 than py2 more standardized and unified some, not to say py2 bad, but because of historical reasons or the beginning of the design thinking problems, become somewhat complex

Print changes, remove unnecessary keywords, in other words can use functions to solve the function, lightweight grammar + rich library, not special, exec and! =, <> is based on the same idea (but for exec, there is a problem to be confirmed, the following said)
int and long merge, new and old class merge, the same reason as above, unify, simply say that if a can achieve B all function, or B can be from a simple construction, then b no need to exist
The return iterator such as Range,map is also based on the same reason, to implement the range of Py2, only a list (range (...) is required, but conversely, py2 to implement an iterator version, you can add only one xrange, and cannot be obtained directly from range (range consumes memory)
String changed to Unicode save, new byte string, but also in order to conform to the times, this seems to be praised very much, however, I would like to say that the coding problem to clarify the most important, confusing people with what can be a problem, only the probability of the size of the difference

Finally, the question of exec, because I do not py3, not in-depth research, I hope to understand the people directly reply, or I have to install a study under.
Py as a dynamic language, the value of its scope variables can be roughly regarded as the {variable name: value} in the form of dict, in fact, the global domain is such, but the function of local variables is special, at compile time to determine the number of, so you can use the array to store, such as
def f ():
A = 1
b = 2
Print A + b
Where A and B is not the form of {a:1,b:2}, the internal implementation is an array, roughly [for] this (of course, not a list, in fact, the CPython virtual machine is a tuple-like object), and then access can be directly offset to do, so the execution speed is obvious, Because most of the operations of most programs are within the function, this situation is also true in most languages
But if there's an exec there's a problem:
def f ():
A = 1
Exec "B = 2"
Print A + b
This allows us to dynamically increment and decrement variables in the local variable domain, which the compiler cannot perceive because the string that exec executes may be dynamically generated and the compiler cannot perceive it, so Py2 's approach to this situation is that if a function has exec, the local variable domain of the function will be accessed differently than the normal function , using the form of dict like global domain
So this requires the compiler to be aware that a function has exec, so it is necessary for exec to be a language keyword, and if as a function, the compiler may be hard to perceive because the PY can assign a function to a variable of another name, or assigning a function name to something else. I think the comparison gives me two points.
    1. Coding issues
    2. Async Coprocessor Joins
RTFM.

This kind of thing directly on the official website to look on, there is no need to ask a question.
Another link: What's New in Python 3.0 Help upstairs to fix some
Google "Python 2 3 differences"
/ http Goo.gl/vs1ou 1. Print is no longer a statement, but a function, such as the original print ' ABC ' is now print (' abc ')
2. In Python 3, there is no old class, only the new class, which means no more like this class Foobar (object): Pass explicitly subclass object
3. The original 1/2 (two integers divided) The result is 0, and now it's 0.5.
4. New string formatting method format supersedes%
5. Raw_input renamed as input
6. Xrange Rename to Range
7.! = Supersedes < >
8. Long is renamed INT
9. Except Exception, E becomes except (Exception) as E
exec becomes a function

There are many other ...
Related Article

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.