Reputation: 47
I know how to substitute individual letters in a normal for loop without using the replace function but I don't know how to do it on a definition with 3 parameters. Per example
def substitute(sentence, target, replacement)
Basically it'll be like substitute("The beach is beautiful", "beach", "sky")
and give back The sky is beautiful. How do you do that without using the replace or find function?
Thanks
def replace_word(sentence, target, replacement):
newSentence = ""
for target in sentence:
if target in sentence:
newSentence += replacement
print(newSentence)
else:
True
return newSentence
Upvotes: 1
Views: 223
Reputation: 537
I think this is what you're looking for.
def replace_word(sentence, target, replacement):
newSentence = ""
for word in sentence.split(" "):
if word == target:
newSentence += replacement
else:
newSentence += word
newSentence += " "
return newSentence.rstrip(" ")
Upvotes: 0
Reputation: 164673
This is one way.
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'
Explanation
str.split
to split your sentence into words.list.append
.if
/ else
.str.join
to join your words with whitespace.Upvotes: 2
Reputation: 3564
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
try this
Upvotes: 0