字符串快速编码——string.maketrans&translate

上一篇 / 下一篇  2011-12-22 15:05:13 / 个人分类:Python小记

玩一个小游戏的时候,遇到字符串解密的问题,一开始,我使用曾经C里的思路。 
 arrary = "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."
for x in arrary:    
    if ord(x) in range(97,122):        
        if ord(x)+2>122:                
            print(chr(ord(x)+2-123+97)),        
        else:                
            print chr(ord(x)+2),    
    else:        
        print x,


发现了一个更简洁的办法。那就是 string.maketrans&translae在Python中,
这2个方法可以使我们对字符串进行快速编码。这两个函数说明如下: 
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.

string.maketrans返回的是一个供translate使用的table,而这里的intab和outtab指的是输入输出2个string之间的转换关系。例如:string.maketrans("map”,“orc") 就是 map ->> orc 的含义。

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.string.translate可以接受的第一个参数为table(maketrans提供),第二个参数为可选,指定要删除的字符串

结合上述2个方法,我们重新编写代码,新代码如下:
arrary = "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."

table = string.maketrans(    "abcdefghijklmnopqrstuvwxyz", "cdefghijklmnopqrstuvwxyzab")

print arrary.translate(table)

.. ps:排版喳喳.. 

TAG: Python python

 

评分:0

我来说两句

日历

« 2024-04-28  
 123456
78910111213
14151617181920
21222324252627
282930    

数据统计

  • 访问量: 4281
  • 日志数: 5
  • 建立时间: 2011-08-26
  • 更新时间: 2011-12-22

RSS订阅

Open Toolbar