1.
string.maketrans(from,to)
Return a translation table suitable for passing totranslate(), that will map each character infrominto the character at the same position into;fromandtomust have the same length.
2.
Return a translation table suitable for passing totranslate(), that will map each character infrominto the character at the same position into;fromandtomust have the same length.
2.
-
string.translate(s,table[,deletechars])
Delete all characters from s that are in deletechars (if present), and then translate the characters using table, which must be a 256-character string giving the translation for each character value, indexed by its ordinal. If table isNone, then only the character deletion step is performed.
例子1:
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!!!
例子2:
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!!!
例子3:
引用自:Python Cookbook 第二版, 1.9节
使用字符串的方法translate,为了使用更方便,对它进行一个封装。
import string
def translator(frm='', to='', delete='', keep=None):
if len(to) == 1:
to = to*len(frm)
trans = string.maketrans(frm, to)
if keep is not None:
#定义一个翻译表allchars,且指定不须翻译。
allchars = string.maketrans('', '')
delete = allchars.translate(allchars, keep.translate(allchars, delete))
def translate(s):
return s.translate(trans, delete)
return translate
NameAndID = 'FuQiang 61450597'
degits_only = translator(keep=string.digits)
print type(degits_only)
ID = degits_only(NameAndID)
print ID
no_digits = translator(delete=string.digits)
name = no_digits(NameAndID)
print name
digits_to_hash = translator(frm=string.digits, to='*')
hideID = digits_to_hash(NameAndID)
print hideID
delete_keep = translator(delete='Fu', keep = 'qiang6145')
partStr = delete_keep(NameAndID)
print partStr
输出结果 :
>>>
<type 'function'>
61450597
FuQiang
FuQiang ********
iang61455
>>>
例子4:
引用自:Python Cookbook 第二版, 1.10节
过滤字符串中不属于指定集合的字符
import string
#maketrans函数是一个创建翻译表的工具函数。
allchars = string.maketrans('', '')
def makefilter(keep):
delchars = allchars.translate(allchars, keep)
def thefilter(s):
return s.translate(allchars, delchars)
return thefilter
if __name__ == '__main__':
filterStr = makefilter('abcdefg')
print filterStr('FuQiang')
输出:
>>>
ag
>>>