Replacing characters in a string using dictionary

2019-08-10 12:43发布

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?

5条回答
姐就是有狂的资本
2楼-- · 2019-08-10 13:01
     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.
查看更多
在下西门庆
3楼-- · 2019-08-10 13:02

Use maketrans and translate:

from string import maketrans
msg.translate(maketrans(''.join(code.keys()), ''.join(code.values())))
查看更多
别忘想泡老子
4楼-- · 2019-08-10 13:02

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.

查看更多
Ridiculous、
5楼-- · 2019-08-10 13:22

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)
查看更多
贼婆χ
6楼-- · 2019-08-10 13:25

You can look at str.translate or do:

''.join(code.get(ch, ch) for ch in msg)
查看更多
登录 后发表回答