###Python中有两个个内建方法,用于解决0-255与相应ascii码转换:
chr()
Return a string of one character with ordinal i; 0 <= i < 256.
也就是,返回代表整数范围内0-255对应的字符。
ord()
Return the integer ordinal of a one-character string.
与chr刚好相反,返回一个字符对应的整数。
code = uncode = {}
for c in (65, 97):
for i in range(26):
code[chr(i+c)] = chr((i+8) % 26 +c)
uncode[chr(i+c)] = chr((i+18) % 26 +c)
s = 'alazyer'
print ''.join([code.get(c) for c in s]) # output: itihgmz
print ''.join([uncode.get(c) for c in 'itihgmz']) # output: alazyer
方法很简单,在循环中,将26个英文字符的大小写,向后移动了8个字符作为密码方法code中,
向后移动18个作为解密密码方法uncode中。如果想加密一个字符串的话,使用code.get(c);
解密的话使用uncode.get(c)。
在Python的this.py中有这样一句:d.get(c, c),
当c不在加密密码中时,使用本身代替,这样实现了对标点符号等的支持。
s = "I love China!"
print ''.join([code.get(c, c) for c in s]) # output: Q twdm Kpqvi!
print ''.join([code.get(c, c) for c in 'Q twdm Kpqvi!']) # output: I love China!