当前位置: 移动技术网 > IT编程>脚本编程>Python > python maketrans and translate

python maketrans and translate

2019年04月19日  | 移动技术网IT编程  | 我要评论

新蔻,哲理文章,黑执事漫画完结了吗

刚刚开始学习python, 于是在openstack hacker养成指南的指示下,登陆了https://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, 里面的空格,引号等不会变, 原样输出。


如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网