user5406649
user5406649

Reputation:

Getting the position of an item in a list from an input (Python)

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.

Upvotes: 2

Views: 2003

Answers (5)

SeanS
SeanS

Reputation: 62

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.

Upvotes: 0

Eugene Yarmash
Eugene Yarmash

Reputation: 149806

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]

Upvotes: 2

Michael
Michael

Reputation: 184

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)

Upvotes: 3

FatmaT
FatmaT

Reputation: 255

 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()]

Upvotes: -1

timgeb
timgeb

Reputation: 78690

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.

Upvotes: -1

Related Questions