Python-string-translate
提供:Dev Guides
Python String translate()メソッド
説明
Python文字列メソッド* translate()*は、table(stringモジュールのmaketrans()関数で構築)を使用してすべての文字が翻訳された文字列のコピーを返し、オプションで文字列_deletechars_で見つかったすべての文字を削除します。
構文
以下は* translate()*メソッドの構文です-
str.translate(table[, deletechars]);
パラメーター
- table -文字列モジュールでmaketrans()ヘルパー関数を使用して、変換テーブルを作成できます。
- deletechars -ソース文字列から削除される文字のリスト。
戻り値
このメソッドは、文字列の翻訳されたコピーを返します。
例
次の例は、translate()メソッドの使用法を示しています。 この下で、文字列内のすべての母音は、その母音の位置に置き換えられます-
#!/usr/bin/python
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/python
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, 'xm')
これにより、次の結果が生成されます–
th3s 3s str3ng 21pl2....w4w!!!