The following is a list of rookie tutorials. These scattered changes need to be noted.
The following things may not be the usual procedures at all, or a little attention on it. But the main difference between 2 and 3 is that mastering the code.
Coding in all programs everywhere, processing is not good, either garbled, or code decoding error. Master the difference between the code, you can master 2 and 3 of the 90% difference, but also only master this ability to switch versions freely.
About coding, there are 3 places, the first line of the program, Python built-in encoding, and software Cmd/pycahrmide's console encoding. That's the three places to figure out.
The default encoding for 2 is sacii,3 is UTF8, which can be confirmed with sys.getdefualencoding (), why the program is setting the Sys.setdefualencoding (' UTF8/GBK '), and that is modifying the default encoding. can also not, but in each decoding time needs to be explicitly written to decode/encode the way.
And then you know that the 2 string is 3 of the bytes,2 Unicode is a 3 string.
Can not freely switch, the first reason is the code, the following differences are not each program will appear these usages, but the code is silently affect each program.
python2.x and 3??. X version Difference
3??. of Python Version 0, often referred to as Python 3000, or simply py3k. This is a large upgrade relative to earlier versions of Python.
In order not to take in too much of a burden, Python 3.0 did not consider downward compatibility when designing.
Many of the programs designed for early Python versions are not performing properly on Python 3.0.
To take care of the existing program, Python 2.6, as a transitional version, basically uses the syntax and library of Python 2.x, taking into account the migration to Python 3.0, allowing the use of some of the syntax and functions of Python 3.0.
The new Python program recommends using the Python version 3.0 syntax.
Unless the execution environment cannot install Python 3.0 or the program itself uses a third-party library that does not support Python 3.0. Currently does not support Python 3.0 third-party library has twisted, py2exe, PiL and so on.
Most third-party libraries are striving to be compatible with Python version 3.0. Even if Python 3.0 is not immediately available, it is recommended that you write a program that is compatible with Python version 3.0 and then execute it using Python 2.6, Python 2.7来.
The changes in Python 3.0 are mainly in the following areas:
Print function
The print statement is gone and replaced by the print () function. Python 2.6 and Python 2.7 support this form of print syntax in parts. In Python 2.6 and Python 2.7, the following three forms are equivalent:
Print "Fish" print ("Fish")#注意print后面有个空格print("Fish")#print () cannot carry any other parameters
However, Python 2.6 has actually supported the new print () syntax:
Fromimport print_functionprint("Fish","Panda", Sep=', ')
Unicode
Python 2 has an ASCII str () type, Unicode () is separate, not a byte type.
Now, in Python 3, we end up with a Unicode (Utf-8) string, and a byte class: Byte and Bytearrays.
Since the python3.x source file uses Utf-8 encoding by default, this makes the following code legal:
>>> China =' Chinese '>>>print(China)
Python 2.x
>>>="I love Beijing Tian ' an gate">>> str' \xe6\x88\x91\xe7\x88\xb1\xe5\x8c\x97\xe4\xba\xac \xe5\xa4\xa9\xe5\xae\x89\xe9\x97\xa8 '>>>= u"I love Beijing Tian ' an gate">>> stru ' \u6211\u7231\u5317\u4eac\u5929\u5b89\u95e8 '
Python 3.x
>>>="I love Beijing Tian ' an gate">>> str' I love Beijing Tian ' an gate '
Division operation
The division in Python is more sophisticated than other languages and has a very complex set of rules. The division in Python has two operators,/and//
First/Division:
In Python 2.x/division is similar to most of the languages we are familiar with, such as Java AH C Ah, the result of dividing an integer is an integer, the fractional part is completely ignored, and the floating-point division retains the part of the decimal point to get the result of a floating-point number.
In Python 3.x/division no longer does this, and the result is a floating-point number for dividing between integers.
Python 2.x:
>>>1/20>>>1.0/2.00.5
Python 3.x:
>>>1/20.5
For//Division, this division, called Floor division, will automatically perform a floor operation on the result of division, consistent in Python 2.x and Python 3.x.
Python 2.x:
>>>-1//2-1
Python 3.x:
>>>-1//2-1
Note that instead of discarding the fractional part, the floor operation is performed, and if you want to intercept the fractional part, you need to use the trunc function of the math module
Python 3.x:
>>>Import math>>> math. Trunc(1/2)0>>> math. Trunc(-1/2)0
Abnormal
Handling Exceptions in Python 3 has also changed slightly, and in Python 3 we now use as as keywords.
The syntax for catching exceptions is changed by except Exc, var to except exc as Var.
Use the syntax except (EXC1, Exc2) as Var to capture multiple categories of exceptions at the same time. Python 2.6 already supports both of these syntaxes.
- 1. In the 2.x era, all types of objects can be thrown directly, in the 3.x era, only objects that inherit from Baseexception can be thrown.
- 2.2.x raise statement using commas to throw object types and parameters separated, 3.x canceled the work of this kind of flower, directly call the constructor to throw objects.
In the 2.x era, exception in the code in addition to the program error, but also often do something common control structure should do, in 3.x can be seen, the designer let the exception becomes more exclusive, only in the case of errors can be used to deal with the exception capture statement.
Xrange
The use of xrange () to create iterative objects in Python 2 is very popular. For example, a for loop or a list/set/dictionary derivation.
This behaves much like a generator (e.g.. "Lazy evaluation"). But this xrange-iterable is infinite, meaning you can traverse infinitely.
Because of its lazy evaluation, if you must not simply not traverse it once, the xrange () function is faster than range (for example for loops). However, it is not recommended that you repeat iterations more than once, because the generator starts from scratch each time.
In Python 3, range () is implemented like xrange () so that a specialized xrange () function no longer exists (xrange () throws a named exception in Python 3).
ImportTimeitn= 10000def test_range< Span class= "pun" > (n return for I in Range (n passdef 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) python2.7. 6timing range () 1000, Best of 3: 433 µs per looptiming xrange () 1000 Loops, Best of Span class= "lit" >3: 350µs per loop
Python 3
Print(' Python ', python_version())print(' \ntiming range () ')%Timeit test_range(n )Python 3.4. 1Timing Range() loops, Best of 3: 520 Μs per loop< /c33>
Print(Xrange(10))---------------------------------------------------------------------------Nameerror Traceback (Most recent callLast)<ipython-input-5-5d8f9b79ea70> in <module> () ---->< Span class= "PLN" > 1 print ( xrange (10nameerror: name ' xrange ' is notdefined
octal literal representation
Octal number must be written 0o777, the original form 0777 can not be used, the binary must be written in 0b111.
A new Bin () function is added to convert an integer into a binary string. Python 2.6 already supports both of these syntaxes.
In Python 3.x, there is only one way to represent octal literals, which is 0o1000.
Python 2.x
>>>0o1000>>>01000
Python 3.x
>>>01000 File"<stdin>",101000^syntaxerror: Invalid token>>>0o1000
Inequality operator
Python 2.x does not equal two ways!! = and <>
Python 3.x removed the <> only! = a kind of notation, fortunately, I never used <> habits
Removed the repr expression '
The inverse quotation mark in Python 2.x is equivalent to the effect of the REPR function
Python 3.x has removed the notation, allowing only the REPR function to be used to make the code look clearer? However, I feel that the opportunity to use repr is very rare, usually only used when debugging, and most of the time, the STR function is used to describe the object with a string.
def SendMail(from_: STR, to: STR, title: str, body : str),bool:pass
Multiple modules are renamed (according to PEP8)
the old name |
new name. |
_winreg |
WinReg |
Configparser |
Configparser |
Copy_reg |
Copyreg |
Queue |
Queue |
Socketserver |
Socketserver |
Repr |
Reprlib |
The Stringio module is now incorporated into the new IO module. Modules such as new, MD5, gopherlib, etc. are removed. Python 2.6 has support for new IO modules.
Httplib, Basehttpserver, Cgihttpserver, Simplehttpserver, cookies, Cookielib are incorporated into the HTTP package.
The EXEC statement is canceled and only the EXEC () function is left. Python 2.6 already supports the EXEC () function.
5. Data type
1) py3.x removed the long type and now has only one integer--int, but it behaves like 2. X version of Long
2) added the bytes type, corresponding to 2. X version of the eight-bit string, define a bytes literal method as follows:
>>>= b' China '>>> type(b)<' bytes '>
str objects and Bytes objects can be converted using the. encode () (str-bytes) or. Decode () (bytes-str) methods.
>>>= b. Decode()>>>' China '>>>= s. Encode()>>> B1 b' China '
3) Dict. Keys (),. Items, and. Values () methods return iterators, and functions such as the previous iterkeys () are discarded. Also remove the Dict.has_key (), with in instead of it.
Python2 and 3 difference, how to do easy switching 2 and 3