Summary of differences between python2 and python 3

osc_ xu7n68ts 2020-11-16 08:54:19
summary differences python2 python python


The project is about to start with python2 Migrate to python3 The environment all simply sums up the difference , I think these are almost , See below for details

Core class differences

Python3 Yes Unicode Native support for characters

Python2 Use in ASCII Code as the default encoding causes string There are two types of str and unicode,Python3 only Support unicode Of string.Python2 and Python3 Byte and character correspond to :

Python3 It's an absolute path import

Python2 In the relative path import It will make the standard library import difficult ( Imagine , There are... In the same directory file.py, Such as How to import this file and standard library at the same time file).

Python3 This point in will be modified , If you need to import files from the same directory, you must Absolute path must be used , Otherwise, you can only use the relevant import method to import .

Python2 There is a difference between the old and the new

Python3 Adopt the new type . The new class declaration requires inheritance object, Multiple inheritance must be applied with new classes

Python3 Use tighter indentation

Python2 In the indentation mechanism of ,1 individual tab and 8 individual space It is equivalent. , the So that you can also allow tab and space Coexist in code . This equivalence mechanism can lead to some IDE There is a problem with the use .

Python3 in 1 individual tab You can only find another tab replace , therefore tab and space Coexistence can lead to misstatement :TabError: inconsistent use of tabs and spaces in indentation

Waste differences

  1. exec Statement by python3 abandoned , Unified use exec function
  2. . execfile Statement by Python3 abandoned , Recommended exec(open("./filename").read())
  3. Inequality operator "<>" By Python3 abandoned , Unified use "!="
  4. long The integer type is Python3 abandoned , Unified use int
  5. xrange Function is Python3 abandoned , Unified use range,Python3 in range The mechanism is also modified and improved Big data set generation efficiency
  6. raw_input Function is Python3 abandoned , Unified use input function
  7. Dictionary variable has_key Function is Python abandoned , Unified use in key word
  8. apply Function is Python3 abandoned
  9. abnormal StandardError By Python3 abandoned , Unified use Exception
  10.  file Function is Python3 abandoned , Unified use open To process files , Can pass io.IOBase Check document type
  11. iterator iterator Of next() Function is Python3 abandoned , Unified use next(iterator)
  12. Python3 These methods no longer return list object :dictionary The associated keys()、values()、items(),zip(), map(),filter(), But it can go through list Forced conversion : 
mydict={"a":1,"b":2,"c":3}
mydict.keys() #<built-in method keys of dict object at 0x000000000040B4C8>
list(mydict.keys()) #['a', 'c', 'b']

Modification of some modules

urillib and urllib2

Python2 Python3
urllib2.urlopen() urllib.request.urlopen()
urllib2.Request() urllib.request.Request()
htmllib.HTMLParser html.parser.HTMLParse
httplib http.client

python3 take python2 Medium urllib2、urlparse、robotparser Incorporated into urllib modular , And modified urllib modular , Which includes 5 Sub module , The common methods in each sub module are as follows :

Module name Common methods
urllib.error ContentTooShortError、URLError、HTTPError
urllib.parse urlparse、_splitparams、urlsplit、urlunparse、urlunsplit、urljoin、urldefrag、unquote_to_bytes、unquote、parse_qs、parse_qsl、unquote_plus、quote、quote_plus、quote_from_bytes、urlencode、to_bytes、unwrap、splittype、splithost、splituser、splitpasswd、splitport
urllib.request install_opener、urlretrieve、 urlcleanup、 request_host、 build_opener、 _parse_proxy、 parse_keqv_list、 parse_http_list、 _safe_gethostbyname、 ftperrors、 noheaders、 getproxies_environment、 proxy_bypass_environment、 _proxy_bypass_macosx_sysconf、 Request
urllib.response addbase、 addclosehook、 addinfo、 addinfourl
urllib.robotparser RobotFileParser

Modify class differences

Floating point division operator “/” and “//” The difference between

“ / ”:

Python2: If two integers are used for operation , The result is plastic surgery , But if one of the two numbers is a floating point number , The result is Floating point numbers ;

Python3: Division for truth , The result is no longer based on the type of number involved in the operation .

“//”:

Python2:

Returns the largest integer less than the result of the division operation ; In terms of type , And "/" Logical consistency of operator return type .

Python3: and Python2 The result is the same .

The difference between exception throwing and catching mechanism

Python2

  1.  raise IOError, "file error" # Throw an exception
  2. except NameError, err: # The catching

Python3

  1.  raise IOError("file error") # Throw an exception
  2. except NameError as err: # The catching

for Difference of variable values in the loop

Python2,for The loop changes the value of the variable with the same name outside

i = 1
print'comprehension: ', [i for i in range(5)])
print'after: i =', i ) #i=4

Python3,for The loop does not change the value of the variable with the same name outside

i = 1
print'comprehension: ', [i for i in range(5)])
print'after: i =', i 

round Function return value difference

Python2,round The function returns float Type values

>>> isinstance(round(15.5),float)
True
>>> round(15.5)
16.0

Python3,round The function returns int Type values

>>> isinstance(round(15.5),int)
True
>>> round(15.5)
16

Compare operators  

Python2 Any two objects in can be compared

>>> 11 < 'test'
True

Python3 Only objects of the same data type can be compared

>>> 11 < 'test'
File "<stdin>", line 1
11 < 'test'
^
IndentationError: unexpected indent

Tool installation problem

windows Environmental Science

Python2 Unable to install mysqlclient.

Python3 Unable to install MySQL-python、 flup、functools32、 Gooey、Pywin32、 webencodings.matplotlib stay python3 Installation error in the environment :The following required packages can not be built:freetype, png. You need to download and install the source package manually . scipy stay Python3 Installation error in the environment ,numpy.distutils.system_info.NotFoundError, Need your own hands Download the corresponding installation package , rely on numpy,pandas It must be strictly based on python edition 、 operating system 、64 Bit or not . function matplotlib Found base package after numpy+mkl Installation failed , You need to download it yourself , There is no download source in China

centos In the environment

Python2 Unable to install mysql-python and mysqlclient package , Report errors :EnvironmentError: mysql_config not found, The solution is to install mysql-devel Package solution . Use matplotlib Report errors :no module named _tkinter, install Tkinter、tk-devel、tc-devel solve . pywin32 Can't be in centos Installation in environment .

 

 

Learning links

Python3 And Python2 What are the differences ?

 

Go with shame , Looking back on the door , But smell the green plum .  ------ Li qingzhao

版权声明
本文为[osc_ xu7n68ts]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database