Explanation: The offset variable is used to track the position in the sentence. To begin with, the offset is -1. On each iteration of the while loop, the offset is set to the next index position for the starting character of the desired word.
For example, let us assume you have the sentence "if we go, we go together" and the word you are searching for is "we".
Before the start of the while loop, the offset is -1, so [offset+1:] will be from 0 (i.e. offset+1) and to the end of the sentence (i.e. :).
The statement sentence.index(word, offset+1) will then set the offset to the starting index position of the matching word (i.e. 3). On each iteration, this will continue until the word is no longer in the remaining sentence or the end of the sentence has been reached.
Thus, for this example, the offset will be -1 before the loop and then 3, 10 at the end of each iteration.
Alternatively: You can use regular expressions. The code below shows how this can be done:
import re
word = input('Enter word: ')
sentence = input('Enter sentence: ')
indexes = []
for match in re.finditer(word, sentence):
indexes.append(match.start())
if len(indexes):
print('\n'.join(map(str, indexes)))
else:
print(f'The word {word!r} is not in the sentence {sentence!r}')
Output: The following output would be displayed if either of the code in the above explanation is executed:
3
10