Code Challenge: String Methods

Hellow fellow coders,

I have a question about one of the string code challenge exercises in the Learn Python 3 course.

The task is the following: Write a function named substring_between_letters that takes a string named word , a single character named start , and another character named end . This function should return the substring between the first occurrence of start and end in word . If start or end are not in word , the function should return word .

For example, substring_between_letters("apple", "p", "e") should return "pl" .

The solution is the below:

def substring_between_letters(word, start, end):

start_index = word.find(start)

end_index = word.find(end)

if start_index > -1 and end_index > -1:

return (word[start_index + 1 : end_index])

else:

return word

I cannot get my head around these two lines of code, particularly the -1 and +1 part:

if start_index > -1 and end_index > -1:

return (word[start_index + 1 : end_index])

Could someone dummy-explain that to me? Apologies if the question is too obvious.

Many thanks in advance everyone!

Please could you have a wee nosey through the following FAQ which describes how to format code for the forums (very helpful) amongst other things such as categorisation and the suggestion to link the lesson of interest.

I think the documentation of the .find method might throw a little light on this-

What happens when the substring you’re searching for cannot be found? To avoid issues with returning a bool or confusion between the truthiness of 0/False and index[0] which is a valid index this method returns -1 when the substring cannot be found.

Can you see what’s being checked in that if statement now?

As for the return statement think about how your index works-

word = 'elephant'
start_idx = word.find('p')  # index 3
end_idx = word.find('n')  # index 6
print(word[start_idx:end_idx])
Out: pha # is this "between" our two letters OR... does it include bits?
1 Like