使用字典中的源替换字符串不能按预期工作

时间:2017-11-10 11:15:29

标签: python

我仍处于Python的学习过程中。这是一个用python编写的代码,它应该加密用户输入的单词或句子。它应该将每个字母或数字更改为下一个字母或数字。但它不起作用。就像我抛出: abcdefghijklmnopqrstuvwxyz1234567890 一样,它会返回: cceeggiikkmmooqqssuuwwyyaa2355679902

我如何解决这个问题,为什么它不起作用?

以下是代码:

   joka = raw_input("PLease enter a word:" )


def replace_all(text, dic):
    for i, j in dic.iteritems():
        text = text.replace(i, j)
    return text

reps = {'a':'b', 'b':'c', 'c':'d', 'd':'e', 'e':'f', 'f':'g', 'g':'h', 'h':'i', 'i':'j', 'j':'k', 'k':'l', 'l':'m', 'm':'n', 'n':'o', 'o':'p', 'p':'q', 'q':'r', 'r':'s', 's':'t', 't':'u', 'u':'v', 'v':'w', 'w':'x', 'x':'y', 'y':'z', 'z':'a', '1':'2', '2':'3', '3':'4', '4':'5', '5':'6', '6':'7', '7':'8', '8':'9', '9':'0', '0':'1'}

j0ka = replace_all(joka, reps)
print j0ka

1 个答案:

答案 0 :(得分:2)

您正在遍历字典,每次只替换一个字母。这会中断,因为您(如果要按顺序迭代)将第一个a替换为b,然后将其替换(b已经跟c,。 ..

由于字典顺序无法保证,因此您看不到效果。

您现在有两种备选方案: 1)遍历字符串并在字典中查找字母:

def replace_all(text, dic):
    return "".join([dic[t] for t in text])

reps = {'a':'b', 'b':'c', 'c':'d', 'd':'e', 'e':'f', 'f':'g', 'g':'h', 'h':'i', 'i':'j', 'j':'k', 'k':'l', 'l':'m', 'm':'n', 'n':'o', 'o':'p', 'p':'q', 'q':'r', 'r':'s', 's':'t', 't':'u', 'u':'v', 'v':'w', 'w':'x', 'x':'y', 'y':'z', 'z':'a', '1':'2', '2':'3', '3':'4', '4':'5', '5':'6', '6':'7', '7':'8', '8':'9', '9':'0', '0':'1'}
joka = "abcdefghijklmnopqrstuvwxyz1234567890"
j0ka = replace_all(joka, reps)
print j0ka

replace_all的长版本:

def replace_all(text, dic):
    replaced_letters = []
    for t in text:
        # iterate letter by letter through the string
        replaced_letters.append(dic[t])
    return "".join(replaced_letters)

或者,您可以使用一些数学来得到您的结果 - 每个字母都有一个相应的ASCII编号。 由于您要实现的目标接近Cesar密码,请查看此资源以获取更多信息。 https://inventwithpython.com/chapter14.html

相关问题