Jake From State Farm
Jake From State Farm

Reputation: 57

Python: Replace First Word That Shows Up with Another Word

I have seven fruits that you are allowed to use in a sentence and you are allowed to write with more then one and as many times as you want. They are Watermelon, Pear, Peach, Orange, Apple, Banana and Grapes. I want to report the sentence back and also replace the first fruit that comes out no matter if the word is shown multiple times and there is multiple fruits that are given in allowed list with Brussel Sprouts as seen below.

In: Apple apple apple what is a watermelon have to do to get an apple?

Out: Brussel sprouts apple apple what is a watermelon have to do to get an apple?

In: The apple likes orange

Out: The brussel sprouts likes orange

Right now I'm messing with this code below, but this only works for one fruit, and I need to check all seven at the same time to see which one is first and to have it replaced.

print sentence.replace("apple", "brussel sprouts", 1)

How do I do this?

Upvotes: 1

Views: 300

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174696

Through re.sub . (.*?) at the first helps to capture all the characters just before to the first fruit. And the pattern (?:Watermelon|Pear|Peach|Orange|Apple|Banana|Grapes) matches the first fruit name. So by replacing the matched characters by the characters inside group index 1 will give you the desired output.

>>> import re
>>> s = "Apple apple apple what is a watermelon have to do to get an apple?"
>>> re.sub(r'(?i)^(.*?)\b(?:Watermelon|Pear|Peach|Orange|Apple|Banana|Grapes)\b', r'\1brussel sprouts', s)
'brussel sprouts apple apple what is a watermelon have to do to get an apple?'
>>> re.sub(r'(?i)^(.*?)\b(?:Watermelon|Pear|Peach|Orange|Apple|Banana|Grapes)\b', r'\1brussel sprouts', 'The apple likes orange')
'The brussel sprouts likes orange'

(?i) called case-insensitive modifier which forces the regex engine to do a case-insensitive match.

Upvotes: 3

aruisdante
aruisdante

Reputation: 9065

There are two separate problems here; The first is find'ing the position of a fruit if it exists in the string. The second is replace'ing the one who was found first. Since I don't want to solve your homework problem for you, I'll simply show you a small example that should get you started in the right direction.

sentence = "Apple apple apple what is a watermelon have to do to get an apple?".lower() # We lowercase it so that "Apple" == "apple", etc.
index = sentence.find("apple")
print(index)
>>> 0
index = sentence.find("banana") # This is what happens when searching for fruit not in sentence
print(index)
>>> -1

Now that you know about find, you should be easily able to figure out how to combine a series of find and replace operations to get your desired output.

Upvotes: 1

Related Questions