无法用字典中的新值替换字符串

Trouble replacing string with new values from a dictionary

我正在尝试按以下方式替换 raw_input string 中的字符:

descriptionsearch - raw_input('text')

def replace(text, dic):
    for i, j in dic.iteritems():
    text = text.replace(i, j)
    return text

replc = {' ': '', 'or': '=', 'and': '==', ',': '=', '+': '=='}

replace(descriptionsearch, replc)
print descriptionsearch

目前我 raw_input "cat or dog" 它 returns 完全一样 "cat or dog".

我不确定为什么此代码不起作用:我将不胜感激解释如何修复我当前使用的代码或更有效地替换 raw_input[=15 中的术语=]

字符串在 Python 中是不可变的,您的 replace 函数不能就地工作,但是 returns 一个新字符串。所以你需要重新分配结果:

descriptionsearch = replace(descriptionsearch, replc)
print descriptionsearch