What does [offset+1:]: mean in this code?

Viewed 51

I am new to coding and was asked to write a program that prompts the user to enter two inputs: some text and a word and to find the indices of the code. While I have completed the code, I am still unsure of the process that goes through. I mainly want to know what offset does in this code.

sentence = input("Enter a sentence: ")
word = input("Enter a word : ")


offset = -1

#use if-else to determine if word is in the sentence
if word in sentence:
    while word in sentence[offset+1:]:
        offset = sentence.index(word, offset+1)
        print(offset)
else:
    print('Not found.')
1 Answers

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
Related