328,636 views
14 votes
14 votes
Write a program that replaces words in a sentence. The input begins with word replacement pairs (original and replacement). The next line of input is the sentence where any word on the original list is replaced. Ex: If the input is: automobile car manufacturer maker children kids The automobile manufacturer recommends car seats for children if the automobile doesn't already have one.

User Saragis
by
2.5k points

1 Answer

19 votes
19 votes

Answer:

In Python:

toreplace = input("Word and replacement: ")

sentence = input("Sentence: ")

wordsplit = toreplace.split(" ")

for i in range(0,len(wordsplit),2):

sentence = sentence.replace(wordsplit[i], wordsplit[i+1])

print(sentence)

Step-by-step explanation:

This gets each word and replacement from the user

toreplace = input("Word and replacement: ")

This gets the sentence from the user

sentence = input("Sentence: ")

This splits the word and replacement using split()

wordsplit = toreplace.split(" ")

This iterates through the split words

for i in range(0,len(wordsplit),2):

Each word is then replaced by its replacement in the sentence

sentence = sentence.replace(wordsplit[i], wordsplit[i+1])

This prints the new sentence

print(sentence)

User Remi
by
3.3k points