Jonathan
Jonathan

Reputation: 47

Create a definition to substitute words in a sentence in Python

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

Answers (3)

Dan
Dan

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

jpp
jpp

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

  • Indentation is crucial in Python. Learn how to use it correctly.
  • Use str.split to split your sentence into words.
  • Initialise a list and add words to the list via list.append.
  • If the word equals your target, then use replacement instead, via if / else.
  • Finally use str.join to join your words with whitespace.

Upvotes: 2

Aniket Bote
Aniket Bote

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

Related Questions