Skip to main content

1.Python2和3部分区别

Python系列文章主要内容来自Reference Link中的链接

Python 2和3的核心区别

不少企业的代码或实际项目升级Python版本的成本很高,所以保留了相当多的Python 2程序。为了阅读与运维这些程序,了解Python 2和3的一些核心区别十分重要

整数除法

  • Python 2中,两个整数的运算结果只能是整数,对于除不尽的情况,Python 2会将结果向下取整,返回小于该结果的最大整数,如12/5的值为2。
  • Python 3中,除法返回浮点数,12/5的结果为2.4。

整形与长整型

  • Python 2中,当整数大于一定范围时,Python 2会自动将整数由整型转换为长整型(long),长整型以数字+L表示,如12345678765434567876543L。
  • Python 3中,长整型被取消,整数都是整型(int)

f字符串

  • Python 3中,引入了f字符串进行格式化,可以在占位符中直接使用已有变量的表达式
a = 100
f"{a=}, a is {a}"
'a=100, a is 100'

字符串类型

  • Python 2中,str类型默认使用ASCII编码,unicode类型使用Unicode编码
  • Python 3中,str类型默认使用Unicode编码,bytes类型使用ASCII编码

不同类型的比较

  • Python 2中,支持,如字符串与数字可以比较大小
  • Python 3中,不支持,字符串与数字不可以比较大小
# 3 > "abc" #在python3中会报错

字典键值对方法的返回类型

  • Python 2中,.keys()、.values()、.items()方法返回列表
  • Python 3中,.keys()、.values()、.items()方法分别返回dict_keys、dict_values、dict_items类型
a = {1: 1, 2: 4}
a.keys(), a.values(), a.items()
(dict_keys([1, 2]), dict_values([1, 4]), dict_items([(1, 1), (2, 4)]))

range(), map(), filter(), zip()函数返回值

  • Python 2中,返回列表
  • Python 3中,返回一个迭代器对象
range(5) > range(0, 5)
zip([1,2,3], [4,5,6] > <zip at 0x10b9a0340>

ord(), chr()函数

  • Python 2中,只支持ASCII字符码即0-255
  • Python 3中,支持所有Unicode码
ord("我")
25105
chr(25105)
'我'

round()函数

  • Python 2中,数字5四舍五入到离0较远的一边
  • Python 3中,数字5近似到偶数
round(1.5)
2
round(2.5)
2

迭代器对象的下一个值

  • Python 2中,.next()方法
  • Python 3中,.__next__()方法
a = [1, 2, 3]
i = a.__iter__()
i.__next__()
1

pathlib模块

  • Python 3中,新增pathlib模块,处理路径
from pathlib import Path
p = Path(".")
p / "123.txt"
PosixPath('123.txt')

urllib模块

  • Python 2中,urllib和urllib2两个模块
  • Python 3中,功能移到urllib.request和urllib.parse两个子模块

运算符@

  • Python 3中,矩阵乘法可以以运算符 @实现:
import numpy as np
a = np.array([[1, 2], [3, 4]])

a @ a
array([[ 7, 10],
[15, 22]])

a.dot(a)
array([[ 7, 10],
[15, 22]])

https://github.com/ddxygq/PyCode/tree/master/Python%E5%9F%BA%E7%A1%80%E8%AF%AD%E6%B3%95

Python 文件I/O | 菜鸟教程 (runoob.com)

Python中命名空间与作用域使用总结 - 奥辰 - 博客园 (cnblogs.com)

python 命名空间和作用域详解 - 知乎 (zhihu.com)

https://nbviewer.org/github/lijin-THU/notes-python3/tree/master/

Python Cookbook 3rd Edition Documentation — python3-cookbook 3.0.0 文档

https://developer.aliyun.com/article/1003286

https://www.jianshu.com/p/2aeee1ed59ec

https://www.liaoxuefeng.com/wiki/1016959663602400/1017624706151424

https://www.xjimmy.com/python-36-serialization.html

#MessagePack序列化传输

https://blog.51cto.com/u_8406447/5769441