使用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)
给我Jimi Hxndrix而不是Jimi Hxndrie。如何获得字母'x'替换为'e'?
It gives me "Jimi Hxndrix" instead of "Jimi Hxndrie". How do I get the letter 'x' to be replaced by 'e' also?
答
$ c> str.translate 或do:
You can look at str.translate
or do:
''.join(code.get(ch, ch) for ch in msg)