我正试图以以下方式替换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"时,它返回完全相同的"cat or dog"。
我不知道为什么这个代码不起作用:如果能解释一下如何修复我目前使用的代码,或者能更有效地替换raw_input
中的术语,我将不胜感激。
字符串在Python中是不可变的,并且replace
函数不能正常工作,而是返回一个新字符串。所以你需要重新分配结果:
descriptionsearch = replace(descriptionsearch, replc)
print descriptionsearch