06 - Python 速查表
← 05-常用模組 | 下一篇 → 07-實戰自動化範例
基本語法
# 變數與型別
x = 10; s = "hello"; f = 3.14; b = True
type(x) # <class 'int'>
isinstance(x, int) # True
# 輸入輸出
print("hello", end="") # 不換行
name = input("名字:") # 等待輸入資料型態速查
# List
lst = [1, 2, 3]
lst.append(4) # 加到末尾
lst.pop() # 刪除末尾
lst.insert(0, 0) # 插入到索引 0
lst.sort() # 排序(in-place)
sorted(lst) # 回傳新 list
len(lst) # 長度
lst[::-1] # 反轉
# Dict
d = {"a": 1}
d.get("b", 0) # 取值,預設 0
d.keys() # 所有 key
d.values() # 所有 value
d.items() # (key, value) 對
"a" in d # 檢查 key 是否存在
# String
s = "hello world"
s.split(" ") # ['hello', 'world']
" ".join(["a","b"]) # 'a b'
s.strip() # 去除首尾空白
s.replace("l","L") # 替換
s.startswith("h") # True
f"{s!r}" # repr 格式控制流程速查
# if
x = 5
result = "big" if x > 3 else "small"
# for
[x**2 for x in range(10) if x % 2 == 0] # list comprehension
{k: v for k, v in d.items()} # dict comprehension
# 常用迭代工具
for i, val in enumerate(lst): # 同時取 index
for a, b in zip(lst1, lst2): # 同時遍歷兩個函式速查
def func(a, b=10, *args, **kwargs):
return a + b
lambda x: x ** 2 # 匿名函式
map(func, lst) # 對每個元素套用函式
filter(lambda x: x>0, lst) # 篩選檔案操作
# 讀檔
with open("file.txt", "r", encoding="utf-8") as f:
content = f.read() # 全部讀入
lines = f.readlines() # 按行讀入 list
# 寫檔
with open("file.txt", "w", encoding="utf-8") as f:
f.write("hello\n")
# 附加寫入
with open("file.txt", "a", encoding="utf-8") as f:
f.write("more content\n")例外處理
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"錯誤:{e}")
except (TypeError, ValueError):
print("型別或值錯誤")
finally:
print("一定會執行")
# 主動拋出例外
raise ValueError("這是錯誤訊息")實用內建函式
abs(-5) # 5
max([1,2,3]) # 3
min([1,2,3]) # 1
sum([1,2,3]) # 6
sorted([3,1,2]) # [1,2,3]
reversed([1,2,3]) # 反轉迭代器
zip([1,2],[3,4]) # [(1,3),(2,4)]
enumerate([a,b]) # [(0,a),(1,b)]
any([F,T,F]) # True(任一為真)
all([T,T,T]) # True(全部為真)Comprehension / f-string 速查
# Comprehension
[x*2 for x in lst] # list
[x for x in lst if x > 0] # 帶篩選
{k: v for k, v in d.items()} # dict
{x for x in lst} # set
# f-string 格式
f"{3.14159:.2f}" # '3.14' 小數 2 位
f"{0.873:.1%}" # '87.3%' 百分比
f"{1234567:,}" # '1,234,567' 千分位
f"{42:05d}" # '00042' 補零
f"{x=}" # 'x=10' debug⚠️ 易踩陷阱速查
# == 比值,is 比「同一物件」;判 None 用 is
x is None # ✅
x == None # ❌ 不要這樣寫
# b = a 不是複製,是別名
b = a.copy() # 淺拷貝(外層獨立)
import copy
b = copy.deepcopy(a) # 深拷貝(連內層獨立)
# 別用可變物件當預設參數
def f(x, bag=None): # ✅
if bag is None:
bag = []← 05-常用模組 | 下一篇 → 07-實戰自動化範例
