作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我已经编写了一个函数来替换句子中的单词,而不使用Python内置的替换方法,问题是我的代码在边缘情况下失败,如果该单词与另一个单词组合,我应该将每个出现的 Maybe 替换为也许。看看我的代码
def replace_all (target,find,replace):
split_target = target.split()
result = ''
for i in split_target:
if i == find:
i = replace
result += i + ' '
return result.strip()
target = "Maybe she's born with it. Maybe it's Maybeline."
find = "Maybe"
replace = "Perhaps"
print replace_all(target, find, replace)
输出是:
Perhaps she's born with it. Perhaps it's Maybeline.
但我期待它打印这个:
Perhaps she's born with it. Perhaps it's perhapsline.
请注意最后一个单词 Maybeline 应该更改为 Maybeline。我已经为此奋斗了一个星期了,任何帮助将不胜感激。
最佳答案
原因是您在空格上进行了分割,因此当您比较 i
时至find
,您正在比较 Maybeline.
至Maybe
。这不会匹配,因此您不会替换该匹配项。
如果您按要查找的值拆分,然后将各个部分与替换字符串连接起来,您将获得许多字符串,在 Maybe
处进行拆分曾经是,您可以使用 replace
加入这些它们之间的字符串:
def replace_all (target,find,replace):
return replace.join(target.split(find))
target = "Maybe she's born with it. Maybe it's Maybeline."
find = "Maybe"
replace = "Perhaps"
print(replace_all(target, find, replace))
> Perhaps she's born with it. Perhaps it's Perhapsline.
关于python - 如何在不使用python替换方法的情况下替换句子中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46760053/
我是一名优秀的程序员,十分优秀!