0

So I created this code to ask a person to input a sentence. After that they type a word in that sentence. Then the code will output the position that word is in.

print("Type a sentence here")
sentence = input("")

sentence = sentence.split()
print("Now type a word in that sentence.")
word = input('')

if word in sentence:
    print("I found",word,"in your sentence.")
else:
    print("That word is not in your sentence.")

print(sentence.index(word))

The problem I am having is that if they put two of the same word in the sentence it only outputs the first one. Please can you help.

Jake
  • 19
  • 5

2 Answers2

0

You could use the built-in enumerate to associate every word in your list sentence with its corresponding position. Then use a list comprehension to get every occurrence of the word in the list.

print([i for i, j in enumerate(sentence) if j == word])

Some further considerations would be that maybe you want to convert your sentence to lower case and remove punctuation before attempting to match your word, such that proper punctuation and capitalization will not trip up your matching. Further, you don't need the '' in input() in order for it to be valid - an empty input() without a prompt is fine.

miradulo
  • 28,857
  • 6
  • 80
  • 93
0

This pb is solved by this script :

import re  
print("Type a sentence here")
sentence = raw_input("") 
print("Now type a word in that sentence.")

word = raw_input('')
words = re.sub("[^\w]", " ",  sentence).split() # using re


position = 1
list_pos = []
for w in words :
   if w == word:
        print position
        list_pos.append(position)
   position += 1
if list_pos:
   print("I found",word,"in your sentence.")
else:
   print("That word is not in your sentence.")
print list_pos
khelili miliana
  • 3,730
  • 2
  • 15
  • 28