0

I want to be able to identify all of the positions where a word appears in a sentence.

For example: Hello my name is Ben and his name is Fred.

If I input 'name' it should return: This word occurs in the places: 3 and 8

Below is my code however it will only return the first value.

text = input('Please type your sentence: ')
sentence = text.split()
word= input('Thank-you, now type your word: ')

if word in sentence:
            print ('This word occurs in the places:', sentence.index(word)+1)
elif word not in sentence:
            print ('Sorry, '+word+' does not appear in the sentence.')
  • This is a duplicate of http://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list – Jérôme Mar 30 '16 at 12:59

3 Answers3

2

This comprehension should do it:

[i+1 for i, w in enumerate(sentence) if w == word]

(+1 because you want first word to be 1 not 0)

Full example:

text = input('Please type your sentence: ')
sentence = text.split()
word = input('Thank-you, now type your word: ')

if word in sentence:
    print ('This word occurs in the places:')
    print([i+1 for i, w in enumerate(sentence) if w == word])
elif word not in sentence:
    print ('Sorry, ' + word + ' does not appear in the sentence.')
Jérôme
  • 13,328
  • 7
  • 56
  • 106
  • I just realized this was already answered here: http://stackoverflow.com/a/6294205/4653485 – Jérôme Mar 30 '16 at 12:59
  • Thank-you but in the compression I need to use the variable 'word' as apposed to the string 'name'. This is so a user can input any word to find a match? –  Mar 30 '16 at 13:12
  • Right. I edited my answer to fix this. I just tested the comprehension on a simplified example, not the whole code. – Jérôme Mar 30 '16 at 13:18
1

You can achieve this with simple list comprehension and enumerate function to find the index. Finally add 1 to match your expected index.

sec = 'Hello my name is Ben and his name is Fred.'
search = input('What are you looking for? ')
print ([i + 1 for i, s in enumerate(sec.split()) if s == search])
Hossain Muctadir
  • 3,546
  • 1
  • 19
  • 33
  • Yes you can do that. Just take input from the user and store it a variable and later you can use it for the comparison. see the corrected code. – Hossain Muctadir Mar 30 '16 at 13:15
0

You cannot do it with an if. You must have one loop, like this:

occurrences = []

for word in sentence:
    if word == target_word:
        occurrences.append(sentence.index(word)+1)

You will have all the occurrences in the array 'occurrences' to print your sentence or you can change 'occurrences' for a 'print' sentence, as your preference.

Please, note that I hasn't run this code, check if it is correct spelled.

Good luck!

Rubén Cotera
  • 52
  • 2
  • 11