[d]一个用到maketrans和tranlate的函数
#简化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
s1 = 'helloworld:8008208820'
num_only = translator(keep = string.digits)
print num_only(s1)
no_num = translator(delete = string.digits)
print no_num(s1)
special_tran = translator(frm = string.digits , to = '#')
print special_tran(s1)
以上translator函数,有些地方不懂,求大牛解析。
特别什么allchars = maketrans('','')
--------------------------
Double行动:
原帖分数:40
帖子加分:40
[解决办法]