字符串函数maketrans(intab,outtab)和translate(table[,deletechars])

鉴于个人E文实在悲剧,虽然能读懂每个单词,但似乎又不能理解说明文档的意思。所以参考了几篇文章之后,决定总结在这里便于个人后面查询。

这两个函数都是字符串处理函数,而且是搭配使用的。maketrans的作用是生成映射表,其返回的结果供translate调用,举个不太恰当的例子:

maketrans规定,以后看到“猪”,都叫“驴”,那相当于在它生成的映射表中,猪映射成驴(当然,程序中的映射表是一些字符,这里只是为了便于理解),在translate使用这张映射表的时候,输出的结果里面就不会有“猪”,因为根据规定,“猪”全部被替换成“驴”了。


如果看了上面两段废话,还是不懂,请深刻的理解下面的官方解释:


string.maketrans(intab, outtab) --> This method returns a translation table that maps each character in the intab string into the character at the same position in the outtab string. Then this table is passed to the translate() function. Note that both intab and outtab must have the same length.


S.translate(table [,deletechars]) -> string. Return a copy of the string S, where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256.


这里我写一个简单的例子:

<pre name="code" class="python">import string
str = "The weather is so gray!"
strTab  = string.maketrans('wisg!','WISG?') #假设我们要把"!"变成"?",把w,i,s,g变成大写
newStr = str.translate(strTab)
print newStr
"""结果: The Weather IS So Gray?"""
 


映射表包含的字符(不含两端的引号):

!"#$%&'()*+,-./:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~”


部分内容来自:http://blog.youkuaiyun.com/lingedeng/article/details/7045443

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值