Python2 and Python3 Differences Summary

Source: Internet
Author: User

"The difference between Python2 and Python3 is summarized, not regularly replenished"

Print

One of the most used statements in program debugging might be print that in Python 2, print is a statement, and Python3 is a function. Some people may have doubts, I also see in the Python2 when the function uses:

# Py2 Print ("hello")  # equivalent Print  ("Hello") # Py3 Print ("hello")

However, what you see is the appearance, so what is the difference between the two expressions above? The output is the same, but essentially, the former is ("hello") treated as a whole, and the latter print() is a function that receives the string as a parameter.

#Py2>>>Print("Hello"," World")('Hello',' World')#Py3>>>Print("Hello"," World") Hello World

This example is more obvious, in Py2, the print statement is followed by a tuple object, and in Py3, the print function can receive multiple positional parameters. If you want to use print as a function in Python2, you can import print_function in the future module

#Py2>>>Print("Hello"," World")('Hello',' World')>>> >>> from __future__ Importprint_function>>>Print("Hello"," World") Hello World

Coding

The default encoding for Python2 is ASSCII, which is one of the reasons why the encoding problem is often encountered in Python2, and why ASSCII is used as the default encoding because the Python language does not appear Unicode. Python 3 defaults to UTF-8 as the default encoding, so you no longer have to write at the top of the file # coding=utf-8 .

# py2>>> sys.getdefaultencoding ()'ascii'#  py3 >>> sys.getdefaultencoding ()'utf-8'

Many articles on the web said that by modifying the default encoding format to solve Python2 coding problem, in fact, this is a big hole, do not do so.

String

The string is one of the biggest changes that makes the coding problem a minimal possibility. In Python2, there are two types of strings, one is Unicode, one is STR, the former represents a text string, the latter represents a sequence of bytes, but there is no obvious boundary between the two, the developer is confused and does not understand the reason for the coding error, but in Python3 the two are strictly differentiated, The string is denoted by str, byte denotes a sequence of bytes, and any data that needs to be written to or transmitted by the network receives only a sequence of bytes, which prevents the problem of coding errors from the source.

Py2 Py3 Performance Conversion
Str Byte Bytes Encode
Unicode Str Character Decode
True and False

True and False are two global variables (first names) in Python2, corresponding to 1 and 0 on numeric values, and since they are variables, they can point to other objects, such as:

# py2>>> True = False>>> truefalse is falsetrue"  x">>> false'x'if  false :...      Print ("? " )... ?

Obviously, the above code violates the design philosophy of Python Explicit is better than implicit. While Python3 corrects this flaw, True and False become two keywords, which always point to two fixed objects and are not allowed to be re-assigned again.

# py3>>> True = 1  "<stdin>", line 1syntaxerror: Can't assign to keyword

Iterators

Many of the built-in functions and methods in Python2 return list objects in Python 3 have been changed to return objects similar to iterators, because the lazy loading of iterators makes it more efficient to manipulate big data. The range and xrange functions in Python2 are combined into range, if they are compatible with both 2 and 3:

Try :     = xrangeexcept:    Pass

In addition, the Dict.keys (), Dict.values () method of the Dictionary object no longer returns a list, but rather is returned as a "view" object that resembles an iterator. The higher-order functions map, filter, and zip return are not list objects either. The Python2 iterator must implement the next method, and Python3 changes to a__next__

Nonlocal

We all know that in Python2 you can global declare a variable as a global variable in a function, but in a nested function it is impossible to declare a variable as a non-local variable, and in Pyhon3, a new keyword is added nonlcoal to make the non-local variable possible.

def func ():     = 1    def  foo ():        =    -foo ()    print(c) func ()     # 1

Can compare the output of the above two pieces of code

def func ():     = 1    def  foo ():        nonlocal c        = +    foo ()    Print (c) func ()    #  A

I want to add ...

Python2 and Python3 Differences Summary

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.