Python 3 將 maketrans 移至 str.maketrans 並統一 translate 行為,請參考 Python 3 版本文檔。本文保留為歷史參考。
from string import maketrans # Python 2
# Python 3: str.maketrans (內建,無需匯入)
maketrans(frm, to) -> translation_table
# frm, to 必須等長字串
bytes.maketrans(frm, to) # Python 3 bytes 版本
translate(table[, deletechars]) 依表轉換,並可選刪除 deletechars 中的字元。
| 特性 | Python 2 | Python 3 |
|---|---|---|
| maketrans 位置 | string.maketrans | str.maketrans / bytes.maketrans |
| translate 參數 | s.translate(table, deletechars) | s.translate(table) (刪除字元在表中映射為 None) |
| Unicode 支援 | 僅 8-bit 字串 (需用 unicode.translate) | 原生 Unicode 字串 |
| 轉換表型別 | 256 字元字串 | 字典 {ord(char): replacement} |
translate 為 C 層單趟掃描,比多次 replace 或正則快數倍。