简体   繁体   中英

update string from a dictionary with the values from matching keys

def endcode(msg,secret_d):
    for ch in msg:
        for key,value in secret_d:
             if ch == key:
                 msg[ch] = value
    return msg
encode('CAN YOU READ THIS',{'A':'4','E':'3','T':'7','I':'1','S':'5'}) 

This is my code. What I am trying to do here is for every characters in a string msg , the function should search in the dictionary and replace it with the mapping string if the character ch is a key in the dictionary secret_d .

If ch is not a key in secret_d than keep it unchanged.

For the example, the final result is should be 'C4N YOU R34D 7H15'

Your function name is endcode but you are calling encode .

But more important, I'll give you a hint to what's going on. This isn't going to totally work, but it's going to get you back on track.

def endcode(msg,secret_d):
    newstr=""
    for ch in msg:
        for key,value in secret_d.iteritems():
            if ch == key:
                newstr=newstr+value
    print(msg)
endcode('CAN YOU READ THIS',{'A':'4','E':'3','T':'7','I':'1','S':'5'}) 

But if you want a complete answer, here is mine.

A few issues:

  • As rb612 pointed out, there's a typo in your function definition ("en d code")
  • you are doing nothing with the return value of your function after calling it
  • msg[ch] is trying to assign items in a string, but that's not possible, strings are immutable. You'll have to build a new string. You cannot "update" it.
  • in order to iterate over (key, value) pairs of a dictionary d , you must iterate over d.items() . Iterating over d will iterate over the keys only.

That being said, here's my suggestion how to write this:

>>> def encode(msg, replacers):
...     return ''.join([replacers.get(c, c) for c in msg])
... 
>>> result = encode('CAN YOU READ THIS',{'A':'4','E':'3','T':'7','I':'1','S':'5'})
>>> result
'C4N YOU R34D 7H15'

Things to note:

  • dict.get can be called with a fallback value as the second argument. I'm telling it to just return the current character if it cannot be found within the dictionary.
  • I'm using a list comprehension as the argument for str.join instead of a generator expression for performance reasons, here's an excellent explanation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM