def translator(frm='', to='', delete='') 、keep=None):
if len(to) == 1:
to = to * len(frm)
trans = string.maketrans(frm, to)
if keep が None でない場合:
allchars = string.maketrans('', '')
delete = allchars.translate(allchars, keep.translate(allchars, delete))
def translation(s):
return s .translate(trans, delete )
return translation call:
コードをコピー
コードは次のとおりです: digits_only = translator( keep=string.digits)
print Digit_only('Chris Perkins : 224-7992')
digits_to_hash = translator(frm=string.digits, to='# ')
print Digit_to_hash(' Chris Perkins : 224-7992')
出力結果: 2247992
Chris Perkins : ###-####