ReZero's Utopia.

凯撒密码(Python)

Word count: 354Reading time: 1 min
2016/11/13 Share

python好叼

#!/usr/bin/python
# -*- coding: UTF-8 -*-

from string import maketrans   # 必须调用 maketrans 函数。

intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)

str = "this is string example....wow!!!";
print str.translate(trantab);

string的maketrans用来创建翻译表
intab待翻译源,outtab翻译结果
import string
string.ascii_uppercase是’ABCDEFGHIJKLMNOPQRSTUVWXYZ’
利用切片可以做凯撒密码 其实就是把字母前面的部分截到第一个要兑换的部分
再把截取的这一部分粘到后面去,比如说

k-m o-q e-g
即每个字母移两位那么就是
abcdefghijklmnopqrstuvwxyz
cdefghijklmnopqrstuvwxyzab
string.ascii_lowercase[2:]即cdefghijklmnopqrstuvwxyz
string.ascii_lowercase[:2]即ab

所以可解

#coding:utf-8
import string      
def caesar_shift(s):  
    table = string.maketrans(string.ascii_lowercase, string.ascii_lowercase[2:] + string.ascii_lowercase[:2])         
    print s.translate(table)  
caesar_shift("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.")

加个循环解26位,再把大小写拼一起,搞定

#coding:utf-8
import string      
def caesar_shift(s):
    for i in range(26) :
        table = string.maketrans(string.ascii_lowercase + string.ascii_uppercase, string.ascii_lowercase[i:] + string.ascii_lowercase[:i] + string.ascii_uppercase[i:] + string.ascii_uppercase[:i])
        print s.translate(table)  
caesar_shift("AAAAedjlak...dadazzzc..fghi")

样例结果

AAAAedjlak...dadazzzc..fghi
BBBBfekmbl...ebebaaad..ghij
CCCCgflncm...fcfcbbbe..hijk
DDDDhgmodn...gdgdcccf..ijkl
EEEEihnpeo...hehedddg..jklm
FFFFjioqfp...ififeeeh..klmn
GGGGkjprgq...jgjgfffi..lmno
HHHHlkqshr...khkhgggj..mnop
IIIImlrtis...lilihhhk..nopq
JJJJnmsujt...mjmjiiil..opqr
KKKKontvku...nknkjjjm..pqrs
LLLLpouwlv...ololkkkn..qrst
MMMMqpvxmw...pmpmlllo..rstu
NNNNrqwynx...qnqnmmmp..stuv
OOOOsrxzoy...roronnnq..tuvw
PPPPtsyapz...spspooor..uvwx
QQQQutzbqa...tqtqppps..vwxy
RRRRvuacrb...ururqqqt..wxyz
SSSSwvbdsc...vsvsrrru..xyza
TTTTxwcetd...wtwtsssv..yzab
UUUUyxdfue...xuxutttw..zabc
VVVVzyegvf...yvyvuuux..abcd
WWWWazfhwg...zwzwvvvy..bcde
XXXXbagixh...axaxwwwz..cdef
YYYYcbhjyi...bybyxxxa..defg
ZZZZdcikzj...czczyyyb..efgh
CATALOG