Python天天美味(9) - translator
2008-05-03 22:10
435 查看
1.string.maketrans设置字符串转换规则表(translation table)
allchars = string.maketrans('', '')#所有的字符串,即不替换字符串aTob = string.maketrans('a','b')#将字符a转换为字符b
2.translate函数进行字符串的替换和删除,第一个参数是字符串转换规则表(translation table),第二个参数是要删除的字符串。比如,要将字符串s中的所有e替换为a,同时要删除所有的o
aTob = string.maketrans('e','a')s = 'hello python'
print s.translate(aTob, 'o')
输出结果:
hall pythn
3.假如我们这样使用
allchars = string.maketrans('', '')k = allchars.translate(allchars, 'a')
allchars表示所有的字符串,而k表示从所有的字符串中去除掉字符a,就是说所有的字符,除了a,因此,我们再调用如下方法时:
s = 'abc'
print s.translate(allchars, k)
字面意思是,输出“字符串s中除去任何不是字符a的字符",即,只输出字符a,因此输出结果为:
a
4.现在,已经不难理解下面这个函数了
import stringdef 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
调用:
digits_only = translator(keep=string.digits)
print digits_only('Chris Perkins : 224-7992')
digits_to_hash = translator(frm=string.digits, to='#')
print digits_to_hash('Chris Perkins : 224-7992')
输出结果:
2247992
Chris Perkins : ###-####
Python 天天美味系列(总)
Python 天天美味(7) - 连接字符串(join %) Python 天天美味(8) - 字符串中的字符倒转Python 天天美味(9) - translator
Python 天天美味(10) - 除法小技巧
Python 天天美味(11) - 可爱的大小写
...
相关文章推荐
- Python天天美味(9) - translator(转)
- Python天天美味(25) - 深入理解yield
- Python天天美味(8) - 字符串中的字符倒转(转)
- Python天天美味(21) - httplib,smtplib
- Python天天美味(29) - 调用VC++的动态链接库(DLL)
- Python天天美味(5) - ljust rjust center
- Python天天美味(32) - python数据结构与算法之堆排序
- Python天天美味(25) - 深入理解yield
- Python天天美味(1) - 交换变量(转)
- Python天天美味(22) - 拷贝对象(深拷贝deepcopy与浅拷贝copy)
- Python天天美味(27) - 网络编程起步(Socket发送消息)
- Python天天美味(6) - strip lstrip rstrip
- Python天天美味(14) - splitlines
- Python天天美味(15) - Python正则表达式操作指南(re使用)(转)
- Python天天美味(36) - 用Python实现Spy++
- Python天天美味(35) - 细品lambda(转)
- Python天天美味(2) - 字符遍历的艺术(转)
- Python天天美味(10) - 除法小技巧(转)
- Python天天美味(23) - enumerate遍历数组
- Python天天美味(10) - 除法小技巧