string下的 maketrans和translate

  在玩python challenge的时候发现一个比较有趣的函数所以记下来。

  问题是这样的

  

g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj

#要把这东西按照g->i,f->h这样格式26个字母转换一遍才知道它要表达什么。

 一开始,博主只能用到自己想到的笨办法。

#-*- coding:utf-8 -*-
import string
alist="g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj"
blist=""
for i in alist:
    if i in string.lowercase:    #string.lowercase表示小写字母
        if ord(i)>120:
            i = chr(ord(i)-24)
        else:
            i= chr(ord(i)+2)
    blist+=i
print blist
#i hope you didnt translate it by hand. thats what computers are for. doing it in by hand is inefficient and that's why this text is so long. using string.maketrans() is recommended. now apply on the url

笨办法用完之后看到提示,可以同string.maketrans()函数,度娘查了下。发现可以string.maketrans()和translate()配合十分好用,先上改装后的demo

#-*- coding:utf-8 -*-
import string
alist="g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj"
mapping=string.maketrans(string.lowercase,string.lowercase[2:]+string.lowercase[:2])
blist = alist.translate(mapping,'')
print blist
#i hope you didnt translate it by hand. thats what computers are for. doing it in by hand is inefficient and that's why this text is so long. using string.maketrans() is recommended. now apply on the url

改装之后十分精简,nice!

另外附上用到函数的语法。

mapping = string.maketrans('asdf','ASDF')
#maketrans函数主要用来创建一一对应关系,这里a->A,s->S,d->D,f->.
#再次强调是一一对应如果mapping = string.maketrans('asdf','ASD')则会报错。"ValueError:maketrans arguments must have same length"
#maketrans可以接受ord()值少于256的字符,可以是字母数字或者特殊符号,但是不可以中文

#使用str.translate()
test_string = "wo shi yi zhi cai niao!"
result = test_string.translate(mapping)
print result
#wo Shi yi zhi cAi niAo! 根据mapping把A大写了
result = test_string.translate(None,'o')
print result
#如果映射为None则不映射,直接删除字母'o'
result = test_string.translate(mapping,'o')
print result
#根据mapping映射,并删除字母o
result = test_string.translate(None)
print result
#不做任何操作,只是说明映射参数是require的即使是None

另外,博主用的是py2.7。不排除py3有新情况如果能有个中文映射就更好了。

原文地址:https://www.cnblogs.com/guapeng/p/4692267.html