[英]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
. 我在这里尝试做的是对于字符串
msg
每个字符,如果字符ch
是字典secret_d
的键,该函数应该在字典中搜索并用映射字符串替换它。
If ch
is not a key in secret_d
than keep it unchanged. 如果
ch
不是secret_d
的键,则secret_d
保持不变。
For the example, the final result is should be 'C4N YOU R34D 7H15'
例如,最终结果应该是
'C4N YOU R34D 7H15'
Your function name is endcode
but you are calling encode
. 您的函数名称是
endcode
但您正在调用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: 一些问题:
msg[ch]
is trying to assign items in a string, but that's not possible, strings are immutable. msg[ch]
试图在字符串中分配项目,但这是不可能的,字符串是不可变的。 You'll have to build a new string. (key, value)
pairs of a dictionary d
, you must iterate over d.items()
. d
(key, value)
对,你必须迭代d.items()
。 Iterating over d
will iterate over the keys only. d
将仅遍历键。 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. dict.get
。 I'm telling it to just return the current character if it cannot be found within the dictionary. str.join
instead of a generator expression for performance reasons, here's an excellent explanation . str.join
作为str.join
的参数而不是生成器表达式,这是一个很好的解释 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.