所有工具
免費

一份可搜尋、可列印的 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 cheat sheet python syntax reference python list methods python dictionary methods python string methods list comprehension python python classes example python file handling
需要協助?
使用此工具時遇到問題?請告訴我們的團隊。
回報問題

將此免費工具新增到你自己的網站 — 複製並貼上下面的程式碼。