简化字符串的 translate 方法的使用
2012-03-19 13:14
309 查看
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版
相关文章推荐
- 【python cookbook】简化字符串的translate 方法的使用
- 1.9 简化字符串的translate方法的使用
- 《Python CookBook2》 第一章 文本 - 检查字符串中是否包含某字符集合中的字符 && 简化字符串的translate方法的使用
- 简化字符串的translate方法的使用
- Python 3.x 字符串的makestrans函数和translate方法使用详解
- Python Cookbook 第二版 汉化版 [Recipe 1.9] 简化字符串 translate 方法的用法
- 总结:数据库连接字符串的使用方法
- lotuscript 使用Mid方法截取字符串
- Java中字符串indexof() 的使用方法
- Android字符串资源文件format方法使用实例
- JavaScript中使用concat()方法拼接字符串的教程
- C#使用非托管代码直接修改字符串的方法
- Java--split拆分使用竖线为分隔符的字符串方法
- JavaScript中使用concat()方法拼接字符串的教程
- OC学习之道:OC对象,字符串和数组的使用方法NSString,NSMutableString ,NSArray,NSMutableArray
- Java中字符串indexof() 的使用方法
- js split str.split(" "); split使用方法 在某处截字符串
- c#中字符串截取使用的方法
- JS判断字符串是否包含某字符串 indexOf()方法使用
- Java使用cmd向main方法传递字符串