Finding The Position Of A Word In A String
With: sentence= input('Enter a sentence') keyword= input('Input a keyword from the sentence') I want to find the position of the keyword in the sentence. So far, I have this code
Solution 1:
This is what str.find()
is for :
sentence.find(word)
This will give you the start position of the word (if it exists, otherwise -1), then you can just add the length of the word to it in order to get the index of its end.
start_index = sentence.find(word)
end_index = start_index + len(word) # if the start_index is not -1
Solution 2:
If with position you mean the nth word in the sentence, you can do the following:
words = sentence.split(' ')
if keyword in words:
pos = words.index(keyword)
This will split the sentence after each occurence of a space and save the sentence in a list (word-wise). If the sentence contains the keyword, list.index() will find its position.
EDIT:
The if statement is necessary to make sure the keyword is in the sentence, otherwise list.index() will raise a ValueError.
Post a Comment for "Finding The Position Of A Word In A String"