使用Python中的字典替换字符串中的字符 [英] Replacing characters in a string using dictionary in Python
本文介绍了使用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)
这篇关于使用Python中的字典替换字符串中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文