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?
xfore, then the first occurrence ofeforx. Thus,Jimi HendrixbecomesJimi Hendrie, thenJimi Hxndrie..replace()is not doing what you think it does.msg = msg.replace(k,code[k])followed byprint k,' ',msgon "Jimi Hendrix fixed the axes" , it prints firstly Jimi Hendrie fieed the aees then Jimi Hxndrix fixxd thx axxs . That's because code is a dictionary that is not iterated in the order 'e' then 'x' but in the order 'x' first and 'e' after. And all the occurences of a character in a string are replaced, not only the first one.