Finding the position of a word in a string

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

Leave a Comment