我知道如何在不使用替换功能的情况下在正常for循环中替换单个字母,但我不知道如何在具有3个参数的定义上执行此操作。每个例子
def substitute(sentence, target, replacement)
基本上它会像substitute("The beach is beautiful", "beach", "sky")
一样回馈天空是美丽的。如果不使用替换或查找功能,如何做到这一点?
感谢
def replace_word(sentence, target, replacement):
newSentence = ""
for target in sentence:
if target in sentence:
newSentence += replacement
print(newSentence)
else:
True
return newSentence
答案 0 :(得分:2)
这是一种方式。
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'
<强>解释强>
str.split
将您的句子分成单词。list.append
将字词添加到列表中。if
/ else
使用替换。str.join
将您的文字加入空格。答案 1 :(得分:1)
import re
def substitue(sentence,target,replacement):
x=re.sub("[^\w]", " ", sentence).split()
x = [word.replace(target,replacement) for word in x]
sent=" ".join(x)
return sent
试试这个
答案 2 :(得分:0)
我认为这就是你要找的东西。
def replace_word(sentence, target, replacement):
newSentence = ""
for word in sentence.split(" "):
if word == target:
newSentence += replacement
else:
newSentence += word
newSentence += " "
return newSentence.rstrip(" ")