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")
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.