maketrans和translate是密切相关的一对方法,str.maketrans()用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。两个字符串的长度必须相同,为一一对应的关系。
translate的说明:
S.translate(table [,deletechars]) -> string
Return a copy of the string S, where all characters occurring
in the optional argument deletechars are removed, and the
remaining characters have been mapped through the given
translation table, which must be a string of length 256.
str.translate()方法以转换表为参数,返回str根据转换表转换后的副本。
translate()的说明:
string.maketrans(intab, outtab) --> This method returns a translation table that maps each character in the intab string into the character at the same position in the outtab string. Then this table is passed to the translate() function. Note that both intab and outtab must have the same length.
table = "".maketrans("\N{bengali digit zero}\N{bengali digit one}a","01A") #对孟加拉数字和小写字母的转换 ""可以是任意字符串
print("\N{bengali digit zero}\N{bengali digit one}abdc".translate(table)) #prints:01Abcd
此方法也可用于删除字符串,将第二个参数相应位制空即可。