gpt4 book ai didi

python - 用字典中的新值替换字符串时遇到问题

转载 作者:太空宇宙 更新时间:2023-11-03 17:49:49 24 4
gpt4 key购买 nike

我正在尝试替换 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 “猫或狗”它返回完全相同的“猫或狗”。

我不确定为什么这段代码不起作用:我非常感谢解释如何修复我当前使用的代码,或者更有效地替换 raw_input 中的术语。

最佳答案

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

descriptionsearch = replace(descriptionsearch, replc)
print descriptionsearch

关于python - 用字典中的新值替换字符串时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29260443/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com