-1

I have been asked to locate where an input word appears in a sentence. I have figured out how to make it case insensitive and chosen which word to find but I am having trouble getting it to print the positions of the word. Here is what I have:

enter code here

sntc = input("Please type in a sentence without punctuation:")
print("This is the sentence you input:",sntc)
wrd = input("Please enter a word you want to search for in the sentence:")
print("The word requested to be seacrhed for is:",wrd)
sntcLow = sntc.lower()
wrd1 = wrd.lower()
SenLst = []
SenLst.append(sntcLow)
print(SenLst)
if any(wrd1 in s for s in SenLst):
    print("Search successful. The word '",wrd1,"' has been found in position(s):")
else:
    print("Search unsuccessful. The word '",wrd1,"' was not found. Please try another word...")
Big Man
  • 11
  • 1
  • 3

2 Answers2

2

To find a particular words position in a sentence you will first have to split the sentence into words and then find the position of that word.

>>> sentence = 'The fat cat ate a fat mouse'
>>> words = sentence.split()
>>> words
['The', 'fat', 'cat', 'ate', 'a', 'fat', 'mouse']

Now you can use index to find the location of fat.

>>> words.index('fat')
1

But as you can already see that index doesn't help much if you have multiple occurrences, since it will only output the first occurrence.

So now what you can do is traverse the list and find if it matches the word.

>>> positions = [indx+1 for indx, word in enumerate(words) if word == 'fat']
>>> positions
[2, 6]
dnit13
  • 2,478
  • 18
  • 35
1

You can use the find method for strings to do this.

It returns -1 if the substring is not found in the string or it returns the index of where the substring starts if found.

If you wanted the actual spanning index (start, end) of where this substring occurs.. You can combine the length of the word with the starting index for the full span.

Pythonista
  • 11,377
  • 2
  • 31
  • 50
  • Can you give me an example of finding the spanning index? – Big Man May 08 '16 at 18:01
  • Finding this only tells me the starting character position of the word. I want to find which positions the word is located in. For example: If the sentence was 'The fat cat ate a fat mouse' then I would want it to print 'The word 'fat' appears in the 2nd and 6th positions. How would I go about doing this? – Big Man May 08 '16 at 18:09