当前位置:首页 > 芯闻号 > 充电吧
[导读]刚刚开始学习python, 于是在OpenStack Hacker养成指南的指示下,登陆了http://www.pythonchallenge.com网站开始做题。 这个上面的题目都比较好玩, 能让人

刚刚开始学习python, 于是在OpenStack Hacker养成指南的指示下,登陆了http://www.pythonchallenge.com网站开始做题。

这个上面的题目都比较好玩, 能让人思考, 这一关的答案就是下一关的入口, challenge1让我学会了字符串处理中maketrans and translate的用法。

import string

hint_str = "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."
"""
len = len(string)
for i in string:
    if i.isalpha():
        new_c = (ord(i)+2)
        if new_c > ord('z'):
            new_c = ord('a')+(ord(i)+1-ord('z'))
        print chr(new_c),
    else:
        print i,

"""
string1 = "abcdefghijklmnopqrstuvwxyz"
string2 = "cdefghijklmnopqrstuvwxyzab"

table = string.maketrans(string1, string2)
print string.translate(hint_str, table)

url = "map"
print string.translate(url, table)
首先maketrans会根据给定的两个参数返回一个字符转换表, 给出的两个参数必须长度相同, 如果转换规则有冲突的, 那么后面的转换规则会覆盖前面的规则。

生成的转换表就可以让 translate函数来调用了,下面是translate的文档说明

translate(s, table, deletions='')
translate(s,table [,deletions]) -> string
 
Return a copy of the string s, where all characters occurring in the optional argument deletions are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256.  The deletions argument is not allowed for Unicode strings.

如果指定了第三个参数, 那么就会在最后返回的字符串中将第三个参数中包括的字符删除掉, translate函数只有存在于table中的字符才会给出转换, 负责会维持原来的字符不变。也就是说在string.translate(hint_str, table)执行过程中, 如果hint_str中含有a, 那么会变成c, 如果含有b会变成d, 里面的空格,引号等不会变, 原样输出。


本站声明: 本文章由作者或相关机构授权发布,目的在于传递更多信息,并不代表本站赞同其观点,本站亦不保证或承诺内容真实性等。需要转载请联系该专栏作者,如若文章内容侵犯您的权益,请及时联系本站删除( 邮箱:macysun@21ic.com )。
换一批
延伸阅读
关闭