Python代码备忘

学习,练习,记录

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

简化字符串的 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版


posted on   sysuoyj  阅读(323)  评论(0编辑  收藏  举报

点击右上角即可分享
微信分享提示