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' 字元:
from string import maketrans # Required to call maketrans function.
print str.translate(trantab, 'xm');
以上執行個體輸出結果:
th3s 3s str3ng 21pl2....w4w!!!