ข้อมูลอ้างอิง Python 3 ที่ค้นหาและพิมพ์ได้ — ไวยากรณ์ โครงสร้างข้อมูล comprehensions ฟังก์ชัน คลาส ไฟล์ และไลบรารีมาตรฐาน ฟรี

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 ไว้ในหน้าเดียวที่ค้นหาได้: ตัวแปรและชนิดข้อมูล string ลิสต์และทูเพิล dict และ set comprehension การควบคุมโฟลว์ ฟังก์ชัน คลาส และไฟล์ ข้อผิดพลาดและโมดูล แต่ละแถวแสดงโค้ดที่ใช้งานได้จริงพร้อมคำอธิบายสั้น ๆ

มันอิงกับ Python ที่เป็นสำนวนเฉพาะตัว — f-string, การแบ่งส่วนข้อมูล (slicing), list และ dict comprehension, การแกะกล่อง (unpacking), argument ค่าเริ่มต้นและคีย์เวิร์ด, context manager และการจัดการข้อยกเว้น — ทำให้มันเป็นตัวทบทวนที่รวดเร็วไม่ว่า Python จะเป็นภาษาประจำวันของคุณหรือเป็นภาษาที่คุณกลับมาใช้เป็นครั้งคราว

เอกสารนี้ฟรีและทำงานฝั่ง client ทั้งหมด กรองแบบสดจากกล่องค้นหา นำทางด้วยเมนูส่วนที่ติดอยู่บนหน้า คัดลอกสนิปเป็ตใด ๆ ด้วยคลิกเดียว และพิมพ์เอกสารอ้างอิงทั้งหมดเมื่อคุณต้องการให้อยู่ข้างคีย์บอร์ด

วิธีใช้ ชีตสรุป Python

  1. ไล่ดูส่วนต่าง ๆ — จาก Variables & types ผ่าน Comprehensions ไปจนถึง Files, errors & modules
  2. พิมพ์ลงในกล่องค้นหาเพื่อกรองทุกสนิปเป็ตแบบสดทั่วทั้งเอกสาร
  3. กระโดดไปยังส่วนอย่าง Dicts & sets โดยใช้สารบัญที่ติดอยู่บนหน้า
  4. คลิกสนิปเป็ตใด ๆ หรือไอคอนคัดลอกของมันเพื่อคัดลอกโค้ด Python
  5. พิมพ์หน้าเพื่อเก็บไว้เป็นข้อมูลอ้างอิง Python 3 แบบออฟไลน์

คำถามที่พบบ่อย

Python 3 สนิปเป็ตใช้สำนวนปัจจุบันเช่น f-string, comprehension, การแกะกล่อง และ context manager จึงรันได้บน Python 3 interpreter สมัยใหม่ทุกตัว

เก้าส่วน: ตัวแปรและชนิดข้อมูล string ลิสต์และทูเพิล dict และ set comprehension การควบคุมโฟลว์ ฟังก์ชัน คลาส และไฟล์ ข้อผิดพลาดและโมดูล — แก่นของไลบรารีมาตรฐานที่คุณใช้ในสคริปต์ประจำวัน

เอกสารทางการมีความครอบคลุมอย่างละเอียด ส่วนเอกสารนี้ตั้งใจให้กระชับ มันแสดงรูปแบบบรรทัดเดียวของแต่ละแพทเทิร์นพร้อมคำอธิบายสั้น ๆ เพื่อให้คุณค้นหา คัดลอก และไปต่อได้ในไม่กี่วินาที

ได้ — คลิกสนิปเป็ตหรือไอคอนคัดลอกที่ปรากฏเมื่อวางเมาส์ แล้วมันจะไปยังคลิปบอร์ดของคุณทันทีพร้อมข้อความยืนยัน "Copied!"

ใช่ ฟรีทั้งหมด มันโหลดในเบราว์เซอร์ของคุณ ไม่ต้องมีบัญชี และพิมพ์ได้

แชร์สิ่งนี้

การค้นหายอดนิยม
python cheat sheet python syntax reference python list methods python dictionary methods python string methods list comprehension python python classes example python file handling
ต้องการความช่วยเหลือ?
พบปัญหากับเครื่องมือนี้หรือไม่? แจ้งทีมงานของเรา
รายงานปัญหา

เพิ่มเครื่องมือฟรีนี้ลงในเว็บไซต์ของคุณเอง — คัดลอกและวางโค้ดด้านล่าง