Yong Hau Kit
Yong Hau Kit

Reputation: 61

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?

Upvotes: 4

Views: 9933

Answers (5)

raton
raton

Reputation: 428

     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.

Upvotes: 0

tehwalrus
tehwalrus

Reputation: 2659

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:

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)

the other answers are library functions which do something like this, but they don't explain where you went wrong.

Upvotes: 0

eyquem
eyquem

Reputation: 27575

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

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

Upvotes: 0

Jon Clements
Jon Clements

Reputation: 142166

You can look at str.translate or do:

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

Upvotes: 9

ecatmur
ecatmur

Reputation: 157374

Use maketrans and translate:

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

Upvotes: 2

Related Questions