str.maketrans() 翻訳テーブルを構築
最終更新:2026-09-22
str.maketrans() 翻訳テーブルを構築
str.maketrans(x[, y[, z]]) は str.translate() で使用する翻訳テーブルを返す。
| カテゴリ | 文字列メソッド |
|---|---|
| 種類 | 組み込み型メソッド |
| Python バージョン | all |
📝 構文
str.maketrans(x[, y[, z]])
⚙️ 引数
| x 必須 | As a single arg, a char-to-char dict; with y/z, the source string to map. |
|---|---|
| y 任意 | A string of equal length to x, mapping chars one-to-one.(デフォルト値:None) |
| z 任意 | A string of chars to delete from the result.(デフォルト値:None) |
戻り値:dict. A translation table usable by str.translate().
元のオブジェクトを変更するか:いいえ(新しいオブジェクトを返す)
💥 例外
TypeError— Raised when x is the only argument and is not a dict.ValueError— Raised when x and y have different lengths.
▶ 例
下のコードを編集し「実行」をクリックすると、出力パネルに結果が表示されます:
実行結果:
h2ll4 w4rld
💡 関連するケース
さらに多くのケースは近日公開予定です。
❓ よくある質問
Q3 つの呼び出し形式は何ですか?
Astr.maketrans(x):x は文字から文字へのマッピング辞書。str.maketrans(x, y):x と y は同じ長さの文字列で 1 文字ずつ対応。str.maketrans(x, y, z):z は削除する文字の集合です。
Qx と y の長さが異なる場合はどうなりますか?
AValueError が発生します。x と y は同じ長さでなければなりません。
Q生成した変換テーブルはどう使いますか?
Astr.translate() に渡します:tbl = str.maketrans('aeiou', '12345')、その後 'hello'.translate(tbl)。