Differences Between Python 2.x and 3.x
Python 3.0, often referred to as Python 3000 or Py3k for short, is a major upgrade compared to earlier versions of Python.
To avoid carrying too much baggage, Python 3.0 was designed without consideration for backward compatibility.
Many programs designed for earlier Python versions cannot run properly on Python 3.0.
To accommodate existing programs, Python 2.6 served as a transitional version, basically using the syntax and libraries of Python 2.x while considering migration to Python 3.0 and allowing the use of some Python 3.0 syntax and functions.
New Python programs are recommended to use Python 3.0 syntax.
Unless the execution environment cannot install Python 3.0, or the program itself uses third-party libraries that do not support Python 3.0. Currently, third-party libraries that do not support Python 3.0 include Twisted, py2exe, PIL, etc.
Most third-party libraries are working hard to become compatible with Python 3.0. Even if Python 3.0 cannot be used immediately, it is recommended to write programs compatible with Python 3.0 and then run them using Python 2.6 or Python 2.7.
The main changes in Python 3.0 are in the following aspects:
print function
The print statement is gone, replaced by the print() function. Python 2.6 and Python 2.7 partially support this form of print syntax. In Python 2.6 and Python 2.7, the following three forms are equivalent:
print "fish"
print ("fish") # 注意print后面有个空格
print("fish") # print()不能带有任何其它参数
However, Python 2.6 actually already supports the new print() syntax, as shown in the following example:
from __future__ import print_function
print("fish", "panda", sep=', ')
If you want to use the Python 3.x print function in Python 2.x, you can import future the package, which disables the Python 2.x print statement and adopts the Python 3.x print function:
Example
list
=
[
"a"
,
"b"
,
"c"
]
list
The print statement in python2.x
[
'a'
,
'b'
,
'c'
]
from
future
import
print_function
Import future package
list
The print statement in Python 2.x is disabled and using it raises an error
File
"
,
line
1
list
^
SyntaxError
: invalid syntax
(
list
)
Use the Python 3.x print function
[
'a'
,
'b'
,
'c'
]
Many compatibility features designed in Python 3.x and Python 2.x can be imported through future this package.
Unicode
Python 2 has the ASCII str() type, and unicode() is separate, not a byte type.
Now, in Python 3, we finally have Unicode (utf-8) strings, as well as byte classes: byte and bytearrays.
Since Python 3.x source files use utf-8 encoding by default, using Chinese text is more convenient:
>>> 中国 = 'china'
>>>print(中国)
china
Python 2.x
>>> str = "我爱北京天安门"
>>> str
'\xe6\x88\x91\xe7\x88\xb1\xe5\x8c\x97\xe4\xba\xac\xe5\xa4\xa9\xe5\xae\x89\xe9\x97\xa8'
>>> str = u"我爱北京天安门"
>>> str
u'\u6211\u7231\u5317\u4eac\u5929\u5b89\u95e8'
Python 3.x
>>> str = "我爱北京天安门"
>>> str
'我爱北京天安门'
Division operation
Division in Python appears quite advanced compared to other languages, with a very complex set of rules. Python has two division operators, / and //
First, let's talk about / division:
In Python 2.x, / division is just like in most familiar languages such as Java and C: dividing integers yields an integer, completely discarding the fractional part, while floating-point division preserves the decimal part and yields a floating-point result.
In Python 3.x, / division no longer does this; when dividing integers, the result is also a floating-point number.
Python 2.x:
>>> 1 / 2
0
>>> 1.0 / 2.0
0.5
Python 3.x:
>>> 1/2
0.5
As for // division, this is called floor division; it automatically performs a floor operation on the division result, and is consistent in both Python 2.x and Python 3.x.
python 2.x:
>>> -1 // 2
-1
python 3.x:
>>> -1 // 2
-1
Note that it does not simply discard the fractional part; it performs a floor operation. If you want to truncate the integer 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
exception
Exception handling in Python 3 has also changed slightly; in Python 3 we now use as as a keyword.
The syntax for catching exceptions has changed from except exc, var to except exc as var.
Using the syntax except (exc1, exc2) as var, you can catch multiple categories of exceptions at once. Python 2.6 already supports both syntaxes.
-
- In the 2.x era, objects of all types could be raised directly; in the 3.x era, only objects inheriting from BaseException can be raised.
-
- The 2.x raise statement uses a comma to separate the type of the raised object from its arguments; 3.x removes this strange syntax and simply calls the constructor to raise the object.
In the 2.x era, exceptions in code, in addition to indicating program errors, were often used to do things that ordinary control structures should do. In 3.x it can be seen that the designers made exceptions more specialized, so that exception-catching statements are only used when an error actually occurs.
Python 2.x: exception handling syntax uses a comma.
try:
# code
except Exception, e:
print e
Python 3.x: exception handling syntax uses as.
try:
# code
except Exception as e:
print(e)
xrange() and range()
Python 2.x: range() returns a list, while xrange() returns a generator (more memory-efficient).
range(5) # 返回 [0, 1, 2, 3, 4]
xrange(5) # 返回 xrange 对象,按需生成数字
Python 3.x: xrange() is removed, and range() returns a generator, saving memory.
range(5) # 返回一个迭代器,按需生成数字
Octal literal representation
Octal numbers must be written as 0o777; the old form 0777 is no longer valid; binary numbers must be written as 0b111.
A new bin() function has been added to convert an integer into a binary string. Python 2.6 already supports both syntaxes.
In Python 3.x, there is only one way to represent an octal literal, which is 0o1000.
python 2.x
>>> 0o1000
512
>>> 01000
512
python 3.x
>>> 01000
File "", line 1
01000
^
SyntaxError: invalid token
>>> 0o1000
512
Inequality operators
In Python 2.x, there are two ways to write not equal: != and <>
Python 3.x removed<>, leaving only != as one form. Fortunately, I never had the habit of using<>.
removed the repr expression ``
In Python 2.x, backticks `` are equivalent to the repr function
In Python 3.x, the `` form was removed and only the repr function is allowed. Is the purpose of this to make the code look clearer? However, I feel the chances of using repr are rare, generally only used when debugging, and most of the time the str function is used to describe objects as strings.
def sendMail(from_: str, to: str, title: str, body: str) -> bool:
pass
Several modules were renamed (according to PEP8)
| Old name | New name |
|---|---|
| _winreg | winreg |
| ConfigParser | configparser |
| copy_reg | copyreg |
| Queue | queue |
| SocketServer | socketserver |
| repr | reprlib |
The StringIO module is now merged into the new io module. Modules such as new, md5, and gopherlib were removed. Python 2.6 already supports the new io module.
httplib, BaseHTTPServer, CGIHTTPServer, SimpleHTTPServer, Cookie, and cookielib were merged into the http package.
The exec statement was removed, leaving only the exec() function. Python 2.6 already supports the exec() function.
5. Data types
1) Py3.X removed the long type; now there is only one integer type - int, but it behaves like the long of version 2.X
2) The bytes type was added, corresponding to the octet string of version 2.X. The way to define a bytes literal is as follows:
>>> b = b'china'
>>> type(b)
str objects and bytes objects can be converted to each other using the .encode() (str -> bytes) or .decode() (bytes -> str) methods.
>>> s = b.decode()
>>> s
'china'
>>> b1 = s.encode()
>>> b1
b'china'
3) The .keys(), .items, and .values() methods of dict return iterators, while the previous iterkeys() and other functions were deprecated. Also removed was dict.has_key(); just use in instead.
6. Standard library reorganization
Python 3.x: Some modules were reorganized or renamed. For example, urllib and urlparse were merged into urllib.
# Python 2.x
import urllib
import urlparse
# Python 3.x
import urllib.parse
7. The iteritems() and items() functions
Python 2.x: Dictionaries have items() and iteritems() methods; items() returns a list, and iteritems() returns an iterator.
d = {'a': 1, 'b': 2}
d.items() # 返回 [('a', 1), ('b', 2)]
d.iteritems() # 返回字典的迭代器
Python 3.x: iteritems() was removed, and items() returns a dictionary view (that is, an iterator).
d = {'a': 1, 'b': 2}
d.items() # 返回 dict_items([('a', 1), ('b', 2)])
8. Module future Supported
Python 3.x: Many Python 2.x features have been removed. If Python 2.x users want to use Python 3.x behavior in their code in advance, they can use future imports to achieve compatibility.
from __future__ import print_function
9. Dictionary ordering
Python 2.x: Dictionaries are unordered (no order is guaranteed).
Python 3.x: Dictionaries are ordered, preserving elements in insertion order.
10. The next() method
Python 2.x: next() is a function, usually used together with iter().
Python 3.x: next() is a built-in function, used the same way as in Python 2.x, but its parameters differ. Python 3.x supports setting a default value via next(iterator, default).