str.translate(table[, deletechars]);
table -- 可以使用在string模組中的 maketrans()輔助函式建立一個轉換表
deletechars -- 從源字串中除去字元列表
下面的範例顯示 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!!!
#!/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!!!