-1
sentence = input("please enter a sentence")    
keyword = input("enter a word you want to find in the string")   
sentence = sentence.lower() 
keyword = keyword.lower()
sentence = sentence.split(' ')
if keyword in sentence:
    pos = sentence.index(keyword)
    pos = pos+1
    print(pos)
else:
    print ("The keyword you entered is not in the sentence you entered")

It has to be able to find the word if it occurs more than once.

Random Davis
  • 6,662
  • 4
  • 14
  • 24
  • @DeepSpace None of the code in that question uses `enumerate()`, which is what OP is asking for. – Random Davis May 19 '16 at 15:21
  • Why does it have to use enumerate()? – Eiko May 19 '16 at 16:06
  • It doesn't but I'm not sure how else to do it – John Perry May 19 '16 at 20:06
  • @JohnPerry Then there are already plenty of answers on how to do this - such as this one, for example: http://stackoverflow.com/questions/4664850/find-all-occurrences-of-a-substring-in-python – Random Davis May 19 '16 at 20:10
  • @RandomDavis that doesn't answer the question how to make it display a keyword form a sentence inputted by a user even if the keyword has been inputted more than once – John Perry May 19 '16 at 20:18

1 Answers1

0

Based on your comments saying that you don't actually need to use enumerate(), but don't know of a way to not use it, your question is misleading. My previous answer, which I deleted, used enumerate() and printed out the index of the keyword in an array of the words, which was incorrect.

In order to output the index of the keyword in your sentence string, as opposed to an array of the words, you could do the following, which I adapted using the link which I posted in a comment:

import re

sentence = raw_input("Please enter a sentence:\n")
keyword = raw_input("Enter a word you want to find in the string: ")

sentence = sentence.lower()
keyword = keyword.lower()

if keyword in sentence:
    positions = [m.start() for m in re.finditer(keyword, sentence)]
    for pos in positions:
        print(pos)
else:
    print ("The keyword you entered is not in the sentence you entered")

This outputs the following:

Please enter a sentence:
blah test test yada 123 test
Enter a word you want to find in the string: test
5
10
24
Community
  • 1
  • 1
Random Davis
  • 6,662
  • 4
  • 14
  • 24