Python3-string-translate
提供:Dev Guides
Python 3 String translate()メソッド
説明
- translate()*メソッドは、table(stringモジュールのmaketrans()関数で構築)を使用してすべての文字が翻訳された文字列のコピーを返し、オプションで文字列_deletechars_で見つかったすべての文字を削除します。
構文
以下は* translate()*メソッドの構文です-
str.translate(table[, deletechars]);
パラメーター
- table -文字列モジュールでmaketrans()ヘルパー関数を使用して、変換テーブルを作成できます。
戻り値
このメソッドは、文字列の翻訳されたコピーを返します。
例
次の例は、translate()メソッドの使用法を示しています。 これにより、文字列内のすべての母音が母音の位置に置き換えられます。
#!/usr/bin/python3
from string import maketrans # Required to call maketrans function.
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
str = "this is string example....wow!!!";
print (str.translate(trantab))
結果
上記のプログラムを実行すると、次の結果が生成されます-
th3s 3s str3ng 2x1mpl2....w4w!!!
例
以下は、文字列から「x」と「m」の文字を削除する例です-
#!/usr/bin/python3
from string import maketrans # Required to call maketrans function.
intab = "aeiouxm"
outtab = "1234512"
trantab = maketrans(intab, outtab)
str = "this is string example....wow!!!";
print (str.translate(trantab))
結果
これは、次の結果を生成します-
th3s 3s str3ng 21pl2....w4w!!!