宁夏电大在线,动漫少女小游戏,强奸新闻
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 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查看网页代码的方法:1、使用“import”导入requests包import requests2、使用requests包的get()函数通过网页...
[阅读全文]
-
-
python如何保存文本文件
python保存文本文件的方法:使用python内置的open()类可以打开文本文件,向文件里面写入数据可以用write()函数,写完之后,使用close()函...
[阅读全文]
-
python如何编写win程序
python可以编写win程序。win程序的格式是exe,下面我们就来看一下使用python编写exe程序的方法。编写好python程序后py2exe模块即可将...
[阅读全文]
-
-
-
-
-
-
网友评论