Python translate()方法

Python 字串 Python 字串


描述

Python translate() 方法根據參數table給出的表(包含 256 個字元)轉換字串的字元, 要過濾掉的字元放到 del 參數中。

語法

translate()方法語法:

str.translate(table[, deletechars]);

參數

  • table -- 翻譯表,翻譯表是通過maketrans方法轉換而來。
  • deletechars -- 字串中要過濾的字元列表。

返回值

返回翻譯後的字串。

實例

以下實例展示了 translate()函數的使用方法:

實例(Python 2.0+)

#!/usr/bin/python from string import maketrans # 引用 maketrans 函數。 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' 字元:

實例(Python 2.0+)

#!/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!!!

Python 字串 Python 字串