0

For example my program stores a sentence, and will then ask the user to input a word from the sentence. However is there a way i can use iterative python to print out the position of the words if it appears twice in the sentence.

sentence = (' hello im jeffery hello who are you?')

print (sentence)

word = input('enter a word from the sentence')

print (word)

split = sentence.split(' ')

if word in split:

    posis = split.index()

print (posis)
roganjosh
  • 12,594
  • 4
  • 29
  • 46
  • See [here](http://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list) – roganjosh Mar 07 '17 at 19:16
  • Possible duplicate of [How to find all occurrences of an element in a list?](http://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list) – Aaron Mar 07 '17 at 19:25

2 Answers2

0

I found this answer elsewhere: How to find all occurrences of an element in a list?

indices = [i for i, x in enumerate(my_list) if x == "whatever"]

For example,

my_list = [1, 1, 2, 3]
indices = [i for i, x in enumerate(my_list) if x == 1]
print(indices)

prints [0, 1]

Community
  • 1
  • 1
Kevin
  • 21
  • 4
0

Make a function that returns a list of matching indices. If the word is not found, it returns an empty list. If only once, it returns only one element in the list. For instance,

def get_positions(word, sentence):
    tokens = sentence.split(' ')
    return [i for i, x in enumerate(tokens) if x == word]

Then you'd just call it to get the result:

sentence = "hello im jeffery hello who are you?"
matching_indices = get_positions("hello", sentence)

if len(matching_indices) < 1:
    print("No matches")
else:
    for i in matching_indices:
        print("Token matches at index: ", i)
Dan
  • 4,488
  • 5
  • 48
  • 75