Replacing characters in a string using dictionary in Python

character, dictionary, python, replace

Solution

You can look at `str.translate` or do:

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

Problem

I have researched about character replacement using dictionaries but I still cannot get my code to work properly. My code goes like this: ``` def encode(code,msg): for k in code: msg = msg.replace(k,code[k]) return msg ``` Now, when I run the code: ``` code = {'e':'x','x':'e'} msg = "Jimi Hendrix" encode(code,msg) ``` It gives me "Jimi Hxndrix" instead of "Jimi Hxndrie". How do I get the letter 'x' to be replaced by 'e' also?

Original source