Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing characters in a string using dictionary in Python

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?

like image 480
Yong Hau Kit Avatar asked Oct 17 '25 10:10

Yong Hau Kit


1 Answers

You can look at str.translate or do:

''.join(code.get(ch, ch) for ch in msg)
like image 166
Jon Clements Avatar answered Oct 18 '25 23:10

Jon Clements



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!