3

我已经使用字典研究了字符替换,但我仍然无法让我的代码正常工作。我的代码是这样的:

def encode(code,msg):  
    for k in code:  
        msg = msg.replace(k,code[k])  
    return msg

现在,当我运行代码时:

code = {'e':'x','x':'e'}
msg = "Jimi Hendrix"
encode(code,msg)

它给了我“Jimi Hxndrix”而不是“Jimi Hxndrie”。如何将字母“x”也替换为“e”?

4

5 回答 5

7

您可以查看str.translate或执行以下操作:

''.join(code.get(ch, ch) for ch in msg)
于 2012-11-29T13:25:38.283 回答
2

使用maketranstranslate

from string import maketrans
msg.translate(maketrans(''.join(code.keys()), ''.join(code.values())))
于 2012-11-29T13:25:32.367 回答
0
     python 3.2
     use your own code it is ok.

     def encode(code,msg):  
                for k in code:  
                       msg = msg.replace(k,code[k],1)  
                return msg

       ##  str.replace(old,new,[,count])
      so when you loop in your code = {'e':'x','x':'e'}
      first it gets the key "x" then the key "e" because dict is not ordered
      so,  "Hendrix" turns into "Hendrie" then "Hendrie" turns into Hxndrix and
     you are not having your result. but if you add 1 in your code
      msg.replace(k,code[k],1) then it only will replace one letter per loop and you                                    
      have your result Try.
于 2012-11-29T16:46:02.453 回答
0

问题是您迭代代码而不是msg

对msg进行迭代是 Jon Clements 的程序中所做的,可以更明确地写为

print ''.join(code[ch] if ch in code else ch for ch in msg)
于 2012-11-29T13:28:10.783 回答
0

你正在交换 x 和 e;它正在覆盖您以前的编辑。

您应该从旧字符串复制到新字符串(或者更确切地说,是一个字符数组,因为正如 Kalle 指出的那样,字符串是“不可变的”/不可编辑的),这样您就不会覆盖已经替换的字符:

def encode(code, message):
    encoded = [c for c in message]
    for i, c in enumerate(message):
        try:
            encoded[i] = code[c]
        except KeyError:
            pass
    return ''.join(encoded)

其他答案是执行类似操作的库函数,但它们没有解释你哪里出错了。

于 2012-11-29T13:28:20.950 回答