【发布时间】:2013-06-28 16:12:20
【问题描述】:
我和一个正在工作的人决定尝试制作一个基本的 Python 程序,该程序将 1) 使字符串混乱 & 2) 使字符串变得混乱。我们的想法是我们可以互相发送绝对垃圾。
我的第一次尝试(我对此很糟糕):
x = ("This is the text")
x1 = x.replace("a","r")
x2 = x1.replace("b","w")
x3 = x2.replace("c","z") #Do this for the whole alphabet
print(x3) #both upper and lower case
然后做同样的事情,但从前到后解读....它可以工作,但它也是 longggggg....
本文代码:http://gomputor.wordpress.com/2008/09/27/search-replace-multiple-words-or-characters-with-python/ 建议创建如下方法:
def replace_all(text,dic):
for i,j in dic.iteritems():
text = text.replace(i,j)
return text
reps = {'a':'r','b':'w','c':'z'} #for the whole alphabet again (yawn)
x = ("This is the text")
txt = replace_all(x, reps)
print(txt)
这行得通吗?我在其他地方看到过 iteritems() 的负面报道??
【问题讨论】:
-
你从哪里读到关于
iteritems()的坏消息?没关系。另外,我不太了解您的问题-您没有尝试过您的代码吗?为什么不知道它是否有效? -
查看
string.translate -
假设情况:您的加密器将 A 替换为 B,将 B 替换为 C。然后“ABBA”转换为“CCCC”,而“BABA”也转换为“CCCC” .您的解密器将无法区分两者!
-
@PauloScardine 实际上 所有 的字母都必须移动才能成为凯撒密码
-
这称为substitution cipher,根据字母频率很容易破解。