所有工具
免费

一份可搜索、可打印的 Python 3 参考——语法、数据结构、推导式、函数、类、文件和标准库。免费。

Variables & types

10
x = 1
Assign a variable (dynamically typed)
x: int = 1
Optional type annotation
a, b = 1, 2
Multiple assignment
type(x)
Get the type of a value
int('42')
Convert a string to an integer
str(42)
Convert a value to a string
isinstance(x, int)
Type check
None
The null/absence value
x = y = 0
Chained assignment
PI: Final = 3.14
Constant hint (typing.Final)

Strings

11
f'Hello {name}'
f-string interpolation
len(s)
String length
s.upper()
Convert to upper case
s.strip()
Remove surrounding whitespace
s.split(',')
Split into a list
','.join(items)
Join a list with a separator
s.replace('a', 'b')
Replace substrings
'a' in s
Membership test
s[1:4]
Slice characters 1 to 3
s[::-1]
Reverse a string
s.startswith('a')
Check the prefix

Lists & tuples

10
a = [1, 2, 3]
Create a list
a.append(4)
Add an item to the end
a.insert(0, x)
Insert at an index
a.pop()
Remove and return the last item
a[1:3]
Slice a sublist
sorted(a, reverse=True)
Return a sorted copy
a.sort(key=len)
Sort in place by a key
len(a)
Number of items
t = (1, 2)
Immutable tuple
first, *rest = a
Unpack with a star

Dicts & sets

10
d = {'k': 'v'}
Create a dictionary
d['k']
Access a value by key
d.get('k', default)
Get with a fallback
d.keys() / d.values()
View keys or values
d.items()
Iterate key/value pairs
{**a, **b}
Merge dictionaries
a | b
Dict/set union operator
del d['k']
Remove a key
s = {1, 2, 3}
Create a set (unique values)
set(a) & set(b)
Set intersection

Comprehensions

8
[x * 2 for x in a]
List comprehension
[x for x in a if x > 0]
Filtered comprehension
{x: x**2 for x in a}
Dict comprehension
{x for x in a}
Set comprehension
(x for x in a)
Generator expression (lazy)
[y for row in m for y in row]
Flatten with nested loops
[a if c else b for x in items]
Conditional value in comprehension
sum(x for x in a)
Aggregate a generator

Control flow

9
if x > 0:\n ...
Conditional (indentation matters)
elif / else:
Additional branches
a if cond else b
Ternary expression
for x in range(10):
Loop over a range
for i, x in enumerate(a):
Loop with an index
for a, b in zip(x, y):
Loop two iterables together
while cond:
Loop while true
break / continue
Exit or skip an iteration
match x:\n case 1: ...
Structural pattern matching (3.10+)

Functions

8
def f(a, b=1): return a + b
Function with a default argument
def f(*args, **kwargs):
Variadic positional + keyword args
f(name='Sam')
Call with a keyword argument
lambda x: x + 1
Anonymous inline function
def f(a: int) -> int:
Type hints for params and return
@decorator
Wrap a function with a decorator
yield value
Produce a value from a generator
global x / nonlocal x
Rebind an outer-scope variable

Classes

9
class A(Base):
Class with inheritance
def __init__(self, x):
Constructor / initializer
self.x = x
Instance attribute
def __str__(self):
String representation
@property
Computed read-only attribute
@staticmethod / @classmethod
Static and class methods
super().__init__()
Call the parent initializer
@dataclass
Auto-generate init/repr/eq
isinstance(obj, A)
Check the instance type

Files, errors & modules

9
with open('f.txt') as fh:
Open a file (auto-closed)
fh.read() / fh.readlines()
Read file contents
open('f.txt', 'w').write(s)
Write to a file
try:\n ...\nexcept ValueError as e:
Catch a specific exception
raise ValueError('bad')
Raise an exception
finally:
Always-run cleanup block
import os
Import a module
from math import sqrt
Import a specific name
import numpy as np
Import with an alias

没有条目匹配“:q”。


关于 Python 速查表

这份 Python 速查表将 Python 3 压缩到一个可搜索的页面中:变量与类型、字符串、列表与元组、字典与集合、推导式、控制流、函数、类,以及文件、错误和模块。每一行都展示可运行的代码,配有简短说明。

它依托于地道的 Python 写法——f-字符串、切片、列表和字典推导式、解包、默认参数和关键字参数、上下文管理器以及异常处理——因此无论 Python 是你的日常语言还是偶尔才用的语言,它都能让你快速复习。

这份速查表免费且完全在客户端运行。用搜索框实时过滤,用固定的章节菜单导航,一键复制任意代码片段,需要时还能打印整份参考资料放在键盘旁。

如何使用 Python 速查表

  1. 浏览各章节——从"变量与类型"到"推导式",再到"文件、错误与模块"。
  2. 在搜索框中输入内容,实时过滤整份速查表中的每个代码片段。
  3. 使用固定目录跳转到某个章节,例如"字典与集合"。
  4. 点击任意代码片段或其复制图标,复制 Python 代码。
  5. 打印页面,获得一份离线的 Python 3 参考资料。

常见问题

Python 3。代码片段使用了当前的惯用写法,比如 f-字符串、推导式、解包和上下文管理器,因此可以在任何现代 Python 3 解释器上运行。

九个章节:变量与类型、字符串、列表与元组、字典与集合、推导式、控制流、函数、类,以及文件、错误和模块——这些是你在日常脚本中会用到的标准库核心内容。

官方文档十分详尽;这份速查表则刻意保持精简。它以简短说明展示每种模式的一行式写法,让你能在几秒钟内找到、复制并继续工作。

可以——点击某个代码片段或悬停时出现的复制图标,它就会直接进入剪贴板,并有"已复制!"提示确认。

是的,完全免费。它在你的浏览器中加载,无需账号,且可以打印。


热门搜索
python 速查表 python 语法参考 python 列表方法 python 字典方法 python 字符串方法 python 列表推导式 python 类示例 python 文件处理
需要帮助?
使用此工具时遇到问题?请告诉我们的团队。
报告问题

将此免费工具添加到你自己的网站 — 复制并粘贴下面的代码。