我知道如何在不使用替换函数的情况下替换普通 for 循环中的单个字母,但我不知道如何在具有 3 个参数的定义上执行此操作。每个例子
def substitute(sentence, target, replacement)
基本上就像 substitute("The beach is beautiful", "beach", "sky")
并返回 The sky is beautiful.在不使用替换或查找功能的情况下如何做到这一点?
谢谢
def replace_word(sentence, target, replacement):
newSentence = ""
for target in sentence:
if target in sentence:
newSentence += replacement
print(newSentence)
else:
True
return newSentence
最佳答案
这是一种方法。
def replace_word(sentence, target, replacement):
newSentenceLst = []
for word in sentence.split():
if word == target:
newSentenceLst.append(replacement)
else:
newSentenceLst.append(word)
return ' '.join(newSentenceLst)
res = replace_word("The beach is beautiful", "beach", "sky")
# 'The sky is beautiful'
说明
- 缩进在 Python 中至关重要。了解如何正确使用它。
- 使用
str.split
将句子拆分为单词。 - 初始化列表并通过
list.append
将单词添加到列表中。 - 如果该单词等于您的目标,则通过
if
/else
使用替换。 - 最后使用
str.join
将单词与空格连接起来。
关于python - 创建定义以替换 Python 句子中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49719514/