2

I have a list with words in it. I want to get the position of the word in the sentence that the user asks for. (I am using python) For example if I had the sentence: "Hello world how are you doing today world?" 'World' occurs in the first and eighth positions. If a user wants to know the positions of the word 'world' in that sentence it would print "The word world is in position 1 and 8". I am aware of the enumerate method but cannot get it to work with an input or an elif statement. I want to get the position(s) of any word in the sentence no matter how many times the word occurs.

planetp
  • 14,248
  • 20
  • 86
  • 160

5 Answers5

2

You could extract the words using a regular expression, then use enumerate() in a list comprehension to find the indexes of the word:

>>> import re
>>> s =  "Hello world how are you doing today world?"
>>> word = input("Enter a word: ").lower()
Enter a word: world
>>> [i for i, v in enumerate(re.findall(r'\w+', s)) if v == word]
[1, 7]
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
2
sentence = "Hello world how are you doing today world?".lower()
searchword = input("Enter word:  ").lower()

newsentence = ''

for character in sentence:
    if character.islower() or character == ' ': newsentence += character

answer = [position for position, word in enumerate(newsentence.split()) if searchword == word]

print(answer)
Michael
  • 174
  • 8
  • I have used your method but it uses the wrong positions. For example 0 when it should be 1. I know why this occurs. I have tried adding 1 to answer but that just caused an error. I was wondering if you know a solution? –  Jan 27 '16 at 23:29
  • List start at position 0. Hello is in position 0 in "Hello world". I won't recommend it but if it is necessary I would just change answer to below. answer = [position + 1 for position, word in enumerate(newsentence.split()) if searchword == word] – Michael Jan 29 '16 at 01:41
0

In your sentence, the word "world" appears in position 1 and 7.

> sentence = "Hello world how are you doing today world?"
> word = input("Enter word:  ").lower()
> answer = [i for i, w in enumerate(sentence.lower().split()) if word in w]
> answer
> [1, 7]

This will work regardless of case or punctuation.

planetp
  • 14,248
  • 20
  • 86
  • 160
SeanS
  • 62
  • 9
-1

With re.finditer and enumerate:

>>> import re
>>> s='Hello world how are you doing today world?'
>>> word='world'
>>> [i for i, w in enumerate(re.finditer('\w+', s)) if w.group()==word]
[1, 7]

We (greedily) find every sequence of characters delimited by non-word characters, iterate over it, and store the index if it is equals to the target word.

timgeb
  • 76,762
  • 20
  • 123
  • 145
-1
 import re
 s='Hello world how are you doing today world?'
 word='world'
 [i for i, w in enumerate(re.findall('\w+', s)) if w.lower() == word.lower()]
FatmaT
  • 255
  • 1
  • 9