Tommy C Tommy C - 7 months ago 8
Python Question

How to make a python program that lists the position/positions of a certain word in a sentence

I'm trying to figure out how to make a python program that highlights the position/positions of a certain inputed word in a sentence and lists what place that word is. For example if the sentence was: "The fat cat sat on the mat"
then the position for the word fat would be Number 2.

Heres what Ive got so far:

varSentence = ("The fat cat sat on the mat")

print (varSentence)

varWord = input("Enter word ")

varSplit = varSentence.split()

if varWord in varSplit:
print ("Found word")
else:
print ("Word not found")

Answer

Use split to convert your sentence int a list of words, enumerate to generate positions, and a list comprehension to generate your results list.

>>> sentence = "The fat cat sat on the mat"
>>> words = sentence.lower().split()
>>> word_to_find = "the"
>>> [pos for pos, word in enumerate(words, start=1) if word == word_to_find]
[1, 6]

If the word is not found your result will be an empty list.