Python String translate()メソッド
例
「S」文字を「P」文字に置き換えます。
#use a dictionary with ascii codes to replace 83 (S) with 80 (P):
mydict
= {83: 80}
txt = "Hello Sam!"
print(txt.translate(mydict))
定義と使用法
このtranslate()
メソッドは、指定された文字が辞書またはマッピングテーブルに記述されている文字に置き換えられた文字列を返します。
この
maketrans()
メソッドを使用して、マッピングテーブルを作成します。
辞書/表に文字が指定されていない場合、その文字は置き換えられません。
辞書を使用する場合は、文字の代わりにASCIIコードを使用する必要があります。
構文
string.translate(table)
パラメータ値
Parameter | Description |
---|---|
table | Required. Either a dictionary, or a mapping table describing how to perform the replace |
その他の例
例
マッピングテーブルを使用して、「S」を「P」に置き換えます。
txt = "Hello Sam!"
mytable = txt.maketrans("S", "P")
print(txt.translate(mytable))
例
マッピングテーブルを使用して、多くの文字を置き換えます。
txt = "Hi Sam!"
x = "mSa"
y = "eJo"
mytable = txt.maketrans(x,
y)
print(txt.translate(mytable))
例
マッピングテーブルの3番目のパラメータは、文字列から削除する文字を記述します。
txt = "Good night Sam!"
x = "mSa"
y = "eJo"
z = "odnght"
mytable = txt.maketrans(x, y, z)
print(txt.translate(mytable))
例
上記と同じ例ですが、マッピングテーブルの代わりにディクショナリを使用しています。
txt = "Good night Sam!"
mydict = {109: 101, 83: 74, 97: 111, 111: None,
100: None, 110: None, 103: None, 104: None, 116: None}
print(txt.translate(mydict))