Chinaunix首页 | 论坛 | 博客
  • 博客访问: 219728
  • 博文数量: 39
  • 博客积分: 945
  • 博客等级: 准尉
  • 技术积分: 532
  • 用 户 组: 普通用户
  • 注册时间: 2012-05-04 17:25
文章分类

全部博文(39)

文章存档

2012年(39)

我的朋友

分类: Python/Ruby

2012-05-24 10:21:17


源自Python cookbook 记录下来,以免今后忘记了。

简化字符串的translate的方法

点击(此处)折叠或打开

  1. #translate_v1.py
  2. #!/usr/bin/python

  3. import string
  4. def translator(frm='', to='', delete='', keep=None):
  5.     if len(to) == 1:
  6.         to = to * len(frm)
  7.     trans = string.maketrans(frm, to)
  8.     if keep is not None:
  9.         allchars = string.maketrans('', '')
  10.         delete = allchars.translate(allchars, keep.translate(allchars, delete))
  11.     
  12.     def translate(s):
  13.         return s.translate(trans, delete)
  14.     return translate
执行如下:

点击(此处)折叠或打开

  1. In [1]: import translate_v1
  2. In [2]: import string
  3. In [3]: digits_only = translate_v1.translator(keep=string.digits)
  4. In [4]: digits_only('Chris Perkins : 224-7992')
  5. Out[4]: '2247992'
  6. In [5]: no_digits = translate_v1.translator(delete=string.digits)
  7. In [6]: no_digits('Chris Perkins : 224-7992')
  8. Out[6]: 'Chris Perkins : -'
  9. In [7]: digits_to_hash = translate_v1.translator(frm='string.digits', to='#')
  10. In [8]: digits_to_hash('Chris Perkins: 224-7992')
  11. Out[8]: 'Chris Perkins: ###-####'


过滤字符串中不属于指定集合的字符

点击(此处)折叠或打开

  1. #!/usr/bin/python

  2. import string

  3. allchars = string.maketrans('', '')
  4. def makefilter(keep):
  5.     delchars = allchars.translate(allchars, keep)
  6.     def thefilter(s):
  7.         return s.translate(allchars, delchars)
  8.     return thefilter


  9. if __name__ == "__main__":
  10.     just_vowels = makefilter('aeiouy')
  11.     print just_vowels('four sore and seven years ago')





阅读(1519) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~