使用Python中的字典替换字符串中的字符

时间:2012-11-29 13:18:12

标签: python dictionary replace character

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

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”?

5 个答案:

答案 0 :(得分:6)

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

''.join(code.get(ch, ch) for ch in msg)

答案 1 :(得分:1)

使用maketranstranslate

from string import maketrans
msg.translate(maketrans(''.join(code.keys()), ''.join(code.values())))

答案 2 :(得分:0)

问题是你在 msg

上迭代代码

迭代 msg 是在Jon Clements的程序中完成的,可以更明确地编写为

print ''.join(code[ch] if ch in code else ch for ch in msg)

答案 3 :(得分: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)

其他答案是库函数,它们执行类似这样的操作,但它们并不能解释您出错的地方。

答案 4 :(得分: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.