Python天天美味(9) - translator

简介:

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 ' )
=   ' hello python '
print  s.translate(aTob,  ' o ' )

输出结果:
hall pythn

3.假如我们这样使用

allchars  =  string.maketrans( '' '' )
=  allchars.translate(allchars,  ' a ' )
allchars表示所有的字符串,而k表示从所有的字符串中去除掉字符a,就是说所有的字符,除了a,因此,我们再调用如下方法时:
=   ' abc '
print  s.translate(allchars, k)
字面意思是,输出“字符串s中除去任何不是字符a的字符",即,只输出字符a,因此输出结果为:
a

4.现在,已经不难理解下面这个函数了

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
调用:
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) - 可爱的大小写 

... 



本文转自CoderZh博客园博客,原文链接:http://www.cnblogs.com/coderzh/archive/2008/05/03/1180705.html,如需转载请自行联系原作者

目录
相关文章
|
14天前
|
存储 JSON JavaScript
「Python系列」Python JSON数据解析
在Python中解析JSON数据通常使用`json`模块。`json`模块提供了将JSON格式的数据转换为Python对象(如列表、字典等)以及将Python对象转换为JSON格式的数据的方法。
31 0
|
14天前
|
JSON API 数据库
「Python系列」Python标准库
Python标准库是Python编程语言自带的一系列模块和功能的集合,这些模块提供了各种常见任务的解决方案,如文件处理、网络编程、数据库接口、图形界面开发、科学计算等。使用标准库可以大大提高开发效率,减少重复劳动。
42 0
|
10月前
|
XML 存储 测试技术
在C#下运行Python:IronPython和Pythonnet
在C#下运行Python可能有不同的原因。其中一些原因包括: 1. 使用C#应用程序中不可用的特定Python功能或库。 2. 结合Python的简单性和表现力以及C#的性能和稳健性,完成不同任务。 3. 与基于Python的系统或服务进行集成。
144 0
|
10月前
|
Python
python|typing模块的介绍
python|typing模块的介绍
78 0
|
10月前
|
Python
Python3 notes
Python3 notes
python-安装easygui的方法
python-安装easygui的方法
124 0
python-安装easygui的方法
|
JSON 前端开发 数据格式
AttributeError,UnboundLocalError,飞桨Python入门,使用python的tkinter库
AttributeError,UnboundLocalError,飞桨Python入门,使用python的tkinter库
115 1
AttributeError,UnboundLocalError,飞桨Python入门,使用python的tkinter库
|
Python
Python - typing 模块 —— NewType
Python - typing 模块 —— NewType
172 0
Python - typing 模块 —— NewType
|
Python
第43天:Python filecmp&difflib模块
第43天:Python filecmp&difflib模块
128 0