源自Python cookbook 记录下来,以免今后忘记了。
简化字符串的translate的方法
- #translate_v1.py
- #!/usr/bin/python
- 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 [1]: import translate_v1
- In [2]: import string
- In [3]: digits_only = translate_v1.translator(keep=string.digits)
- In [4]: digits_only('Chris Perkins : 224-7992')
- Out[4]: '2247992'
- In [5]: no_digits = translate_v1.translator(delete=string.digits)
- In [6]: no_digits('Chris Perkins : 224-7992')
- Out[6]: 'Chris Perkins : -'
- In [7]: digits_to_hash = translate_v1.translator(frm='string.digits', to='#')
- In [8]: digits_to_hash('Chris Perkins: 224-7992')
- Out[8]: 'Chris Perkins: ###-####'
过滤字符串中不属于指定集合的字符
- #!/usr/bin/python
- import string
- allchars = string.maketrans('', '')
- def makefilter(keep):
- delchars = allchars.translate(allchars, keep)
- def thefilter(s):
- return s.translate(allchars, delchars)
- return thefilter
- if __name__ == "__main__":
- just_vowels = makefilter('aeiouy')
- print just_vowels('four sore and seven years ago')
阅读(1510) | 评论(0) | 转发(0) |