Brandon Lee Ornelas
Brandon Lee Ornelas

Reputation: 11

Replacing a word or words in a sentence by word or words given by user

I am trying to replace a given word in a sentence with an inputted word that the user gives. I'm having trouble figuring out how to replace word individually as seen in the code and example below:

def replace(line, word):
    new_line = ''
    for i in range(line.count(word)):
        new_word = input('Enter ' +word+ ' : ')
        new_line = line.replace(word, new_word)
    return new_line
def main():
    print(replace('the noun verb past the noun', 'noun'))

    main()

Output when running the above via the terminal:

$ python3 madlib.py

Enter NOUN : DOG

Enter NOUN : DUCK

the DUCK VERB PAST the DUCK

If the two supplied words were DOG and DUCK, I would like it to produce "the DOG verb past the DUCK".

Upvotes: 0

Views: 1633

Answers (2)

Satish Prakash Garg
Satish Prakash Garg

Reputation: 2233

You can use replace() maxreplace(third argument) to pass the number of replacements need to be done, something like this :

def replace_word(line, word):
    new_line = line     
    for i in range(line.count(word)):
        new_word = input('Enter ' +word+ ' : ')
        new_line = new_line.replace(word, new_word, 1)  # replacing only one match
    return new_line
def main():
    print(replace_word('the noun verb past the noun', 'noun'))

main()

This will result in :

>>> Enter noun : dog
>>> Enter noun : duck
>>> the dog verb past the duck

You can refer to this documentation for more understanding.

Note : It is not good practice to use names for custom functions that are already identified by python interpreter. So, use replace_word() or something like this instead of naming your function replace().

Upvotes: 1

ajmartin
ajmartin

Reputation: 2409

def replace(line, word):
    new_line = line
    for i in range(line.count(word)):
        new_word = input('Enter ' +word+ ' : ')
        start_index = new_line.find(word) #returns the starting index of the word
        new_line = new_line[:start_index] + new_word + new_line[start_index + len(word):]
    return new_line
def main():
    print(replace('the noun verb past the noun', 'noun'))
main()

Upvotes: 0

Related Questions