SoFunction
Updated on 2025-03-01

In-depth analysis of the main differences between the version

Version Description

Python 3.0 was not designed to be compatible with earlier versions

As a transitional version, Python 2.6 basically uses Python's syntax and libraries, and also considers the migration to Python 3.0, allowing the use of some Python 3.0 syntax and functions.
 

Programming is not recommended unless it is for the purpose of using old project code or only supported third-party libraries.

Dead print function

In Python 2.6 and Python 2.7, the following three forms are equivalent:

print "fish"
print ("fish") #Note that there is a space behind the printprint("fish") #print()Cannot take any other parameters

But you can only use the latter two. The print statement is discarded by python3, and you can only use the print function

Unicode

In Python3, strings are Unicode (utf-8) encoding and support Chinese as identifiers.

In python2, it is ASCII encoding. You need to change the character set to support Chinese normally. So you will see #-- coding: UTF-8 -- in the .py file.

#python3>>> China = 'china' 
>>>print(China) 
china
#python2>>> str = "I love Beijing * Square"
>>> str
'\xe6\x88\x91\xe7\x88\xb1\xe5\x8c\x97\xe4\xba\xac\xe5\xa4\xa9\xe5\xae\x89\xe9\x97\xa8'
>>> str = u"I love Beijing * Square"
>>> str
u'\u6211\u7231\u5317\u4eac\u5929\u5b89\u95e8'

Division operation

Single slash /, in Python 2, integer phase divides into integers, and floating point decimal phase divides into floating point; in Python 3, the result is always floating point numbers.

#python3
>>print(10/5)
2.0

Double slashes //, Python 2 and 3 are the same, both are the division result and the decimal part is removed.

>>print(10//3)
3

Exception handling

Python2middletry:...except ERR,e:...,existPython3middle改为了try:...except ERR as e:...
#Python3
try:
 open('','r')
except Exception as e:
 print(e) #Don't use it here, either

In Python 2, you can use raise IOError, "file error" or raise IOError("file error") to trigger an exception.

In Python 3, only raise IOError("file error") can be used.

Exception StandardError is abandoned by Python3, and Exception is used uniformly

xrange and range

The xrange method is no longer used in Python3, only the range method

range returns a list in Python2, and range iterable in Python3

a=range(10)
print(a)
print(list(a))

Output

range(0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Octal literal

Only 0o... format can be used in Python3. An error will be thrown for the 01000 format, while both can be used in Python2.

>>> 01000
 File "<stdin>", line 1
 01000
  ^
SyntaxError: invalid token
>>> 0o1000
512

Unequal operator

There are two unequal operators != and <> in Python2. <> is removed in Python3, and only the != symbol indicates inequality.

repr

In Python 2, double backticks `` can replace the repr function. In Python 3, tables with double backticks removed are methods. Only repr methods can be used.

Module name change

The StringIO module is now merged into the new io module. New, md5, gopherlib and other modules were deleted.

httplib, BaseHTTPServer, CGIHTTPServer, SimpleHTTPServer, Cookie, cookielib are merged into the http package.
The exec statement is cancelled, leaving only the exec() function.

long type

In Python2, long is an integer with a larger value range than int. In Python3, long type is cancelled, and the value range of int is expanded to the previous long type range.

bytes type

Python3 has added a bytes type, using string definitions starting with b:

>>> b = b'china' 
>>> type(b) 
<type 'bytes'> 

str object and bytes object can be used.encode() (str -> bytes) or .decode() (bytes -> str)The methods are transformed into each other.

>>> s = () 
>>> s 
'china' 
>>> b1 = () 
>>> b1 
b'china' 

dict type

The dict's .keys(), .items and .values() methods in Python3 return iterators, while previous functions such as iterkeys() are abandoned.

At the same time, dict.has_key() is also removed, which can be replaced by in.

di={
 'a':1,
 'b':2,
 'c':3
}
for item in ():
 print(item)
print('c' in di)

Output

('gggg', {'a1': 1})
('b', 12)
True

Next() function and .next() method

my_generator = (letter for letter in 'abcdefg')
In python 2, you can use next(my_generator) and my_generator.next() methods.
In python 3, you can only use next(my_generator) method.

List comprehension

The [n for n in a,b] syntax is no longer supported, and it is changed to [n for n in (a,b)] or [n for n in [a,b]]

a=1
b=2
c=[n for n in [a,b]]
print(c)

Output [1,2]

input

In python 2, the type of input input is int, onlyraw_input()The type of input is str.
The types of input input in python 3 are all str, removedrow_input()method.

Comparison symbol

Any two objects in Python 2 can be compared, 11 < 'test' returns True
In Python 3, only objects of the same data type can be compared. 11 < 'test' report error, regular judgment needs to be called, and changed toimport re;11 < int('test') if ('^[0-9]+$').match('test') else 0Otherwise, an error will be reported

other

The exec statement is discarded by python3, and the exec function is used uniformly.

The execfile statement is discarded by Python3, recommended to useexec(open("./filename").read())

These methods in Python3 no longer return list objects: dictionary-associated keys(), values(), items(), zip(), map(), filter(), but can be cast by list

The next() function of iterator is abandoned by Python3, and next(iterator) is used uniformly.

The file function is discarded by Python3. Open is used to process files in a unified way. You can check the file type

The apply function is abandoned by Python3

Summarize

The above is the main difference between the version introduced by the editor and I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!