wak*_*ude 2 python dictionary replace key input
我正在尝试制作一个程序,该程序将接受输入,查看这些单词中的任何一个是否是先前定义的字典中的键,然后用它们的条目替换任何找到的单词。难点在于“看看单词是否是关键”。例如,如果我尝试替换该字典中的条目:
dictionary = {"hello": "foo", "world": "bar"}
Run Code Online (Sandbox Code Playgroud)
当给定输入“hello world”时,如何使其打印“foo bar”?
不同的方法
def replace_words(s, words):
for k, v in words.iteritems():
s = s.replace(k, v)
return s
s = 'hello world'
dictionary = {"hello": "foo", "world": "bar"}
print replace_words(s, dictionary)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12442 次 |
| 最近记录: |