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?
Use
maketrans
andtranslate
:you're swapping x and e; it is overwriting your previous edits.
You should copy from an old string to a new one (or rather, an array of chars, since as Kalle pointed out strings are "immutable"/not editable), so that you don't overwrite characters you've already replaced:
the other answers are library functions which do something like this, but they don't explain where you went wrong.
The problem is that you iterate on code instead on msg
Iterating on msg is what is done in Jon Clements' program, which can be written more explicitly as
You can look at
str.translate
or do: