鉴于个人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.
<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