简化字符串的 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 = string.maketrans('', '')
delete = allchars.translate(allchars, keep.translate(allchars, delete))

def translate(s):
return s.translate(trans, delete)

return translate
In [6]: from translator import *

In [7]: digits_only = Translator(keep = string.digits)

In [8]: digits_only('Chris Perkins:224-7992 ')
Out[8]: '2247992'
In [10]: digits_to_hash = Translator(frm = string.digits, to = '#')

In [11]: digits_to_hash('Chris Perkins:224-7992')
Out[11]: 'Chris Perkins:###-####'

来源:Python Cookbook 第2版


你可能感兴趣的:(translate)