Python 备忘单是 Python 3 编程语言的单页参考表
入门
介绍
- Python 官方网站 (python.org)
- Python 文档 (docs.python.org)
- Y 分钟学会 Python (learnxinyminutes.com)
- Python 中的正则表达式 (jaywcjlove.github.io)
控制台打印
1 | print("Hello, World!") |
著名的“Hello World”程序在 Python 中的实现
变量
1 | age = 18 # 年龄是 int 类型 |
- Python 不能在没有赋值的情况下声明变量
- 变量可以存放不同类型的值
内置数据类型
序列指一批有序的元素,集合指一批无序且不重复的元素
| :- | :- |
|---|---|
str | 文本/字符串(Text) |
int, float, complex | 数值(Numeric) |
dict | 映射/键值对(Mapping) |
list, tuple, range | 序列(Sequence) |
set, frozenset | 集合(Set) |
bool | 布尔值/逻辑值(Boolean) |
bytes, bytearray,memoryview | 二进制数据(Binary) |
查看: 数据类型
字符串切片
1 | msg = "Hello, World!" |
查看: 字符串
列表
1 | mylist = [] |
查看: 列表
判断
1 | num = 200 |
查看: 判断
循环
1 | for item in range(6): |
查看: 循环
函数
1 | def my_function(): |
查看: 函数
文件处理
1 | with open("myfile.txt", "r", encoding='utf8') as file: |
查看: 文件处理
算术
1 | result = 10 + 30 # => 40 |
/ 表示 x 和 y 的商,// 表示 x 和 y 的底商,另见 StackOverflow
加等于
1 | counter = 0 |
f-字符串 (Python 3.6+)
1 | website = 'Quick Reference' |
查看: f-字符串
Python 数据类型
字符串
1 | hello = "Hello World" |
查看: 字符串
数值
1 | x = 1 # 整数 |
只要内存足够,可以容纳无限大(小)的数值
布尔值
1 | my_bool = True |
bool 是 int 的子类
列表
1 | list1 = ["apple", "banana", "cherry"] |
查看: 列表
元组
1 | my_tuple = (1, 2, 3) |
类似列表,但自身不可变
集合
1 | set1 = {"a", "b", "c"} |
类似列表,但里面的元素是无序而不重复的
字典
1 | empty_dict = {} |
键-值对,一种像 JSON 那样对象
类型转换
转换为整数
1 | x = int(1) # 得到 1 |
转换为浮点数
1 | x = float(1) # 得到 1.0 |
转换为字符串
1 | x = str("s1") # 得到 "s1" |
Python 字符串
下标访问
1 | hello = "Hello, World" |
循环
1 | for char in "foo": |
对字符串 for-in 可以得到每个字符(类型还是字符串)
切割字符串
1 | ┌───┬───┬───┬───┬───┬───┬───┐ |
1 | s = 'mybacon' |
1 | s = 'mybacon' |
1 | s = 'mybacon' |
步长
1 | s = '12345' * 5 |
获取长度
1 | hello = "Hello, World!" |
len() 函数返回字符串的长度
重复多次
1 | s = '===+' |
存在性判断
1 | s = 'spam' |
判断 “spam” 这个字符串是否在其它字符串里
字符串拼接
1 | s = 'spam' |
格式化
1 | name = "John" |
1 | name = "John" |
format() 方法
1 | txt1 = "My name is {fname}, I'm {age}".format(fname="John", age=36) |
转义符号
| 转义符号 | 对应的操作 |
|---|---|
\\ | 输出反斜杠 |
\' | 输出单引号 |
\" | 输出双引号 |
\n | 换行 |
\t | 水平制表符 |
\r | 光标回到首位 |
\b | 退格 |
控制台输入
1 | name = input("Enter your name: ") |
从控制台获取输入数据
头尾判断
1 | # 是否以 H 开头 |
插入分隔符拼接
1 | "、".join(["John", "Peter", "Vicky"]) |
Python f-字符串 (Python 3.6+)
f-字符串 用法
1 | website = 'Reference' |
它从 Python 3.6 开始可用,另见: 格式字符串字面值
填充对齐
1 | f'{"text":10}' # 使用空格填充到指定长度 |
按类型输出
1 | f'{10:b}' # 输出二进制数值 |
显示正负号
1 | f'{12345:+}' # 显示正数的正号 |
其它
1 | f'{-12345:0=10}' # 负数 |
Python 列表
定义
1 | li1 = [] |
生成
1 | list(filter(lambda x : x % 2 == 1, range(1, 20))) |
添加元素
1 | li = [] |
切片
列表切片的语法:
1 | a_list[start:end] |
切片
1 | a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster'] |
省略索引
1 | a[:4] |
间隔索引
1 | ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster'] |
删除
1 | li = ['bread', 'butter', 'milk'] |
列表边界
1 | li = ['a', 'b', 'c', 'd'] |
连接
1 | odd = [1, 3, 5] |
排序和反转
1 | li = [3, 1, 3, 2, 5] |
计数
1 | li = [3, 1, 3, 2, 5] |
重复
1 | li = ["re"] * 3 |
搜索
1 | nums = [40, 36, 89, 2, 36, 100, 7, -20.5, -999] |
if-elif-else
1 | number = int(input('输入一个整数:')) |
三目运算
1 | scope = int(input('输入百分制成绩:')) |
注意条件是放在中间的
Python 循环
一般形式
1 | primes = [2, 3, 5, 7] |
带索引
1 | animals = ["dog", "cat", "mouse"] |
while 循环
1 | x = 0 |
跳出循环
1 | x = 0 |
跳过一轮循环
1 | for index in range(3, 8): |
范围循环
1 | for i in range(4): |
使用 zip()
1 | name = ['Pete', 'John', 'Elizabeth'] |
列表生成式
1 | result = [x**2 for x in range(10) if x % 2 == 0] |
Python 函数
基础
1 | def hello_world(): |
返回
1 | def add(x, y): |
位置参数
1 | def varargs(*args): |
args 的类型是 tuple
关键字参数
1 | def keyword_args(**kwargs): |
kwargs 的类型是 dict
返回多个
1 | def swap(x, y): |
默认值
1 | def add(x, y=10): |
匿名函数
1 | # => True |
Python 解包
- 解包是将一个
序列
内的多个元素依次重新分配到有限个容器的过程,这只发生在 变量赋值、参数传递 和 生成式生成 过程中。 _这个变量是命令行交互中最后一次计算得到的值,在程序设计中一般用来存放解包时不再需要的值。
但它的含义会因赋值而改变,比如标准库 gettext 中常用作动态获取翻译文本。
等量解包
1 | ip, port = "127.0.0.1", 80 |
适量解包
1 | ip, _, port = "127.0.0.1:80".rpartition(":") |
_ 也是一个单一变量,不允许解包多个元素,因此变量与值必须一一对应。
过量解包
1 | major, minor, *parts = "3.10.2.beta".split(".") |
这里的 * 就是收集序列在解包过程中多出来的元素,
只能有一个,与向函数传递位置参数时的 * 别无二致。
解包取左边
1 | major, minor, *_ = "3.10.2.beta".split(".") |
解包取两边
1 | major, *_, level = "3.10.2.beta".split(".") |
解包取右边
1 | *_, micro, level = "3.10.2.beta".split(".") |
解包集合
1 | a, b, *_ = {3, 2, 1} |
集合
中的元素是无序的,因此解包结果不能轻易确定。
解包迭代器
1 | a, b, *_ = range(3) |
支持
迭代器
协议的对象也可被解包。
解包字典
1 | a, b, *_ = dict(a=1, b=2, c=3) |
生成式中的解包
1 | chars = (*"abc", *"def", "g", "h") |
- 仅在列表/元组生成式中可以使用多个
* - 仅在字典生成式中可以使用多个
**
迭代中解包
1 | students = [ |
函数中的解包
1 | def version(major, minor, *parts): |
Python 模块
导入模块
1 | import math |
从一个模块导入
1 | from math import ceil, floor |
导入一个模块的全部
1 | from math import * |
给模块起别名
1 | import math as m |
浏览模块的函数和属性
1 | import math |
Python 文件处理
读取文件
逐行
1 | with open("myfile.txt") as file: |
带行号
1 | file = open('myfile.txt', 'r') |
字符串
写入一个字符串
1 | contents = {"aa": 12, "bb": 21} |
读取一个字符串
1 | with open('myfile1.txt', "r+") as file: |
对象
写一个对象
1 | contents = {"aa": 12, "bb": 21} |
读取对象
1 | with open('myfile2.txt', "r+") as file: |
删除文件
1 | import os |
检查和删除
1 | import os |
删除文件夹
1 | import os |
Python 类和继承
定义
1 | class MyNewClass: |
构造函数
1 | class Animal: |
方法
1 | class Dog: |
类变量
1 | class MyClass: |
super() 函数
1 | class ParentClass: |
1 | child_instance = ChildClass() |
repr() 方法
1 | class Employee: |
用户定义的异常
1 | class CustomError(Exception): |
多态性
1 | class ParentClass: |
重写
1 | class ParentClass: |
继承
1 | class Animal: |
Python 数据模型
更多请移步 https://docs.python.org/zh-cn/3/reference/datamodel.html
自定义类创建
参见 自定义类创建 。
1 | from typing import Any |
上下文管理器
参见 上下文管理器 。
1 | from typing import Any |
特殊方法
下表使用 -> * 代表返回值类型是任意的,或者需要视情况而定,实际上并不存在这种写法。
诸如 -> str 仅表示绝大多数情况下应当返回 str 类型,或者推荐返回 str 类型。
没有 -> 的方法一般没有返回值。
参见 https://docs.python.org/zh-cn/3/reference/datamodel.html
| 语句 | 特殊方法 | 备注 | |
|---|---|---|---|
repr(obj) | __repr__(self) -> str | 详见 repr() 。 | |
str(obj) | __str__(self) -> str | 详见 str 类型 。 | |
bytes(obj) | __bytes__(self) -> bytes | 详见 bytes() 。 | |
format(obj, spec) | __format__(self, spec) -> str | 详见 format()、格式化字符串字面值、格式规格迷你语言 。 | |
hash(obj) | __hash__(self) -> int | 详见 hash() 。 | |
bool(obj) | __bool__(self) -> bool | 未定义时调用 obj.__len__() != 0 ,若 __len__() 也未定义,则所有对象都被视为 True 。另见 bool() 。 | |
dir(obj) | __dir__(self) -> list | 返回值必须是一个序列,dir() 会把返回的序列转换为列表并对其排序。 | |
Object[key] | __class_getitem__(cls, key) -> * | 不建议用于除了 模拟泛型类型 以外的用途,避免 IDE 误判。 |
- 自定义实例及子类检查,参见 https://docs.python.org/zh-cn/3/reference/datamodel.html#customizing-instance-and-subclass-checks
| 语句 | 特殊方法 | 备注 | |
|---|---|---|---|
isinstance(instance, class) | class.__instancecheck__(self, instance) -> bool | 如果 instance 应被视为 class 的一个(直接或间接)实例则返回真值。 | |
issubclass(subclass, class) | class.__subclasscheck__(self, subclass) -> bool | 如果 subclass 应被视为 class 的一个(直接或间接)子类则返回真值。 |
| 语句 | 特殊方法 | 备注 | |
|---|---|---|---|
obj < other | __lt__(self, other) -> bool | ||
obj <= other | __le__(self, other) -> bool | ||
obj == other | __eq__(self, other) -> bool | 默认返回 obj is other ,如果结果为 False ,则会返回 NotImplemented 。 | |
obj != other | __ne__(self, other) -> bool | 默认返回 not obj.__eq__(other) 。 | |
obj > other | __gt__(self, other) -> bool | ||
obj >= other | __ge__(self, other) -> bool |
| 语句 | 特殊方法 | 备注 | |
|---|---|---|---|
obj.name | __getattr__(self, name) -> * | 优先调用。当抛出 AttributeError 时转向调用 __getattribute__() 。 | |
obj.name | __getattribute__(self, name) -> * | 参见 自定义属性访问 避免无限递归。 | |
obj.name = value | __setattr__(self, name, value) | ||
del obj.name | __delattr__(self, name) | 仅在 del obj.name 对于该对象有意义时才应该被实现。 |
| 语句 | 特殊方法 | 备注 | |
|---|---|---|---|
len(obj) | __len__(self) -> int | ||
op.length_hint(obj) | __length_hint__(self) -> int | 在使用标准库 operator 的 length_hint() 时会被调用(Python 3.4+)。 | |
obj[key] | __getitem__(self, key) -> * | 需要抛出 IndexError 以便正确地结束 for 循环。 | |
obj[key] | __missing__(self, key) -> * | 仅在 dict 的子类找不到键时被调用(不能重写 __getitem__ 方法)。 | |
obj[key] = value | __setitem__(self, key, value) | a[1:2] = b 实际上是 a[slice(1, 2, None)] = b ,其它情形及在其余方法中同理。详见 slice() 。 | |
del obj[key] | __delitem__(self, key) | ||
| 调用途径有很多 | __iter__(self) -> Iterator | 在需要创建一个 迭代器 时被调用,例如使用 iter() 、 for 循环 。最好返回一个新对象,因为迭代器在语义上是一次性的。若返回 self ,则必须实现 __next__() 方法。 | |
reversed(obj) | __reversed__(self) -> * | 详见 reversed() 。 | |
item in obj | __contains__(self, item) -> bool | 对于未定义该方法的对象在 in 和 not in 时,参考 成员检测运算 。 |
| 语句 | 特殊方法 | 备注 | |
|---|---|---|---|
+obj | __neg__(self) -> * | ||
-obj | __pos__(self) -> * | ||
~obj | __invert__(self) -> * | ||
abs(obj) | __abs__(self) -> * | ||
int(obj) | __int__(self) -> * | ||
float(obj) | __float__(self) -> * | ||
complex(obj) | __complex__(self) -> * | ||
round(obj) | __round__(self) -> int | 详见 round() 。 | |
round(obj) | __round__(self, ndigits) -> * | 详见 round() 。 | |
math.ceil(obj) | __ceil__(self) -> int | 详见标准库 math 的 ceil() 。 | |
math.floor(obj) | __floor__(self) -> int | 详见标准库 math 的 floor() 。 | |
math.trunc(obj) | __trunc__(self) -> int | 详见标准库 math 的 trunc() 。 | |
__index__(self) -> int | 需要无损地将数值转换为整数的时候会被调用。详见 这里 。 | ||
obj + other | __add__(self, other) -> * | ||
obj - other | __sub__(self, other) -> * | ||
obj * other | __mul__(self, other) -> * | ||
obj @ other | __matmul__(self, other) -> * | 为第三方库而生的矩阵乘法运算符,这里提了一嘴。(Python 3.5+) | |
obj / other | __truediv__(self, other) -> * | ||
obj // other | __floordiv__(self, other) -> * | ||
obj % other | __mod__(self, other) -> * | ||
divmod(obj, other) | __divmod__(self, other) -> tuple | divmod(a, b) 返回一个元组 (a // b, a % b) ,详见 divmod() 。 | |
obj ** exp | __pow__(self, exp) -> * | ||
pow(obj, exp, mod) | __pow__(self, exp, mod) -> * | pow(base, exp, mod) 比 pow(base, exp) % mod 更高效。 | |
obj << other | __lshift__(self, other) -> * | ||
obj >> other | __rshift__(self, other) -> * | ||
obj & other | __and__(self, other) -> * | ||
obj ^ other | __xor__(self, other) -> * | ||
obj | other | __or__(self, other) -> * | ||
other + obj | __radd__(self, obj) -> * | 仅当 obj 未定义 __add__() 或其返回 NotImplemented ,且与 other 互相都没有继承关系时,调用 other 的 __radd__() 。详见 这里 。 | |
other - obj | __rsub__(self, obj) -> * | 以下,如此类推。 | |
other * obj | __rmul__(self, obj) -> * | ||
other @ obj | __rmatmul__(self, obj) -> * | ||
other / obj | __rtruediv__(self, obj) -> * | ||
other // obj | __rfloordiv__(self, obj) -> * | ||
other % obj | __rmod__(self, obj) -> * | ||
divmod(other, obj) | __rdivmod__(self, obj) -> tuple | ||
other ** obj | __rpow__(self, obj) -> * | ||
__rpow__(self, obj, mod) -> * | pow(obj, other, mod) 不会尝试调用 other.__rpow__(obj, mod) ,因为强制转换规则会太过复杂。 | ||
other << obj | __rlshift__(self, obj) -> * | ||
other >> obj | __rrshift__(self, obj) -> * | ||
other & obj | __rand__(self, obj) -> * | ||
other ^ obj | __rxor__(self, obj) -> * | ||
other | obj | __ror__(self, obj) -> * | ||
obj += other | __iadd__(self, other) -> * | 若方法已定义,则 a += b 等价于 a.__iadd(b) ;若未定义,则回退到 a + b 选择 x.__add__(y) 和 y.__radd__(x) 。 | |
obj -= other | __isub__(self, other) -> * | 以下,如此类推。 | |
obj *= other | __imul__(self, other) -> * | ||
obj @= other | __imatmul__(self, other) -> * | ||
obj /= other | __itruediv__(self, other) -> * | ||
obj //= other | __ifloordiv__(self, other) -> * | ||
obj %= other | __imod__(self, other) -> * | ||
obj **= exp | __ipow__(self, other) -> * | ||
obj <<= other | __ilshift__(self, other) -> * | ||
obj >>= other | __irshift__(self, other) -> * | ||
obj &= other | __iand__(self, other) -> * | ||
obj ^= other | __ixor__(self, other) -> * | ||
obj |= other | __ior__(self, other) -> * |
Python 类型标注 (Python 3.5+)
变量
1 | string: str = "ha" |
变量
1 | result: str = 1 + 2 |
错误的类型标注不会影响正常运行,也不会报错
参数
1 | def say(name: str, start: str = "Hi"): |
位置参数
1 | def calc_summary(*args: int): |
表示 args 的所有元素都是 int 类型的。
返回值
1 | def say_hello(name) -> str: |
多种可能的返回值
1 | from typing import Union |
表示返回值可能是 int,也可能是 str 。
关键字参数
1 | def calc_summary(**kwargs: int): |
表示 kwargs 的所有值都是 int 类型的。
多个返回值
1 | def resp200() -> (int, str): |
多种可能的返回值 (3.10+)
1 | def resp200(meaningful) -> int | str: |
自 Python 3.10 起可用。
属性
1 | class Employee: |
标注自己
1 | class Employee: |
这里表示 set_name() 返回了一个 Employee 对象。
标注自己 (3.11+)
1 | from typing import Self |
标注一个值为类型的参数
1 | from typing import TypeVar, Type |
标注一个值为函数的参数
1 | from typing import TypeVar, Callable, Any |
各种各样的
注释
1 | # 这是单行注释 |
1 | """ 可以写多行字符串 |
1 | ''' 可以写多行字符串 |
生成器
1 | def double_numbers(iterable): |
生成器可帮助您编写惰性代码
要列出的生成器
1 | values = (-x for x in [1,2,3,4,5]) |
处理异常
1 | try: |
pyenv & pipenv
pvenv 用于管理python版本,pipenv 用于管理项目包版本
pyenv
1 | 安装 pyenv |
1 | 安装 python 版本 |
pipenv
1 | 安装 pipenv |
1 | 将 pipenv 命令加入到系统环境变量 $PATH 中 (Unix and MacOS) |
1 | 指定 python 版本 |
另见
- Python 官方网站 (python.org)
- Python 文档 (docs.python.org)
- Y 分钟学会 Python (learnxinyminutes.com)
- Python 中的正则表达式 (jaywcjlove.github.io)





