I.Hull
I.Hull

Reputation: 11

How to return the multiple indexes of word using .index in Python

I am struggling with the command .index in Python. I want to be able to enter a sentence and then Python to return the multiple indexes of the word I choose. For example if I enter the sentence "i love you you love me we all love barney" and then choose the word "love" I want it to return "2","5","9". But instead my code only will return the first one, "2".

sentence = input("Enter a sentence")
word = input("Enter the word")
position = sentence.index(word)
print(position)

Please can you help me edit this code so it return more than one index of the chosen word.

Thanks

Upvotes: 0

Views: 1882

Answers (4)

user6999902
user6999902

Reputation:

Use enumerate (Note: the index of the first word will be 0) and split:

s = "i love you you love me we all love barney"
for word_index, word in enumerate(s.split()):
    if word == "love":
        print(word_index)

Output:

1
4
8

Upvotes: 1

Afsal Salim
Afsal Salim

Reputation: 486

indices = [i+1 for i, x in enumerate(sentence.split()) if x == word]

indices contains all the position

Upvotes: 0

Rohan Amrute
Rohan Amrute

Reputation: 774

You can split the words in the sentence with a space and then search for a particular word.

For example:

textSplit = sentence.split(' ')
for i in range(len(textSplit)):
   if textSplit[i] == word:
      print i+1

Upvotes: 0

amin
amin

Reputation: 1441

.index only return the first occurrence. You can try this:

position = [idx+1 for idx,w in enumerate(sentence.split()) if w == word]
print(position)

Upvotes: 0

Related Questions