【发布时间】:2017-04-01 13:35:30
【问题描述】:
想要替换字符串中的某些单词但不断得到以下结果:
字符串:"This is my sentence."
用户输入他们想要替换的内容:"is"
用户输入他们想要替换单词的内容:"was"
新字符串:"Thwas was my sentence."
我如何确保它只替换单词“is”而不是它找到的任何字符串?
代码功能:
import string
def replace(word, new_word):
new_file = string.replace(word, new_word[1])
return new_file
非常感谢任何帮助,谢谢!
【问题讨论】:
-
很好的发现。我搜索了一个重复项,但使用的是“替换”一词,而不是“查找”。
-
我也是:python replace words not partial words。我认为“不偏词”一词是这里的关键。
-
至少现在涵盖了“替换”部分:)
-
@TadhgMcDonald-Jensen 诀窍是用谷歌搜索关键字,只是我每次都忘记了。 SO 引擎很好,因为您可以使用 sqbrackets 过滤标签,但 google 更适合一般搜索,并且 99% 的时间 SO 答案首先弹出!
标签: python string for-loop replace conditional-statements