How do I create a more universal code for this question?

For this question in the String review:

https://www.codecademy.com/paths/data-science/tracks/dscp-python-fundamentals/modules/dscp-python-strings/lessons/python-functions-strings-cc/exercises/substring-between-letters

I have a code that works for the problem but if I was given the word “appple” it would not work.
What would be a more universal solution?

def substring_between_letters(word,start,end):
x = word.find(start)
y = word.find(end)
if start in word and end in word:
return word[x+1:y]
else:
return word

Perhaps you could work out how you’d solve this without code first. So search for start, then do… and so on. Once you have that it’s a case of translating into something in Python.

So in words how would you solve this problem?

I’m not 100% sure what addition you’re after (what’s wrong with that word?) but the docs for the method you use wiil likely be helpful- https://docs.python.org/3/library/stdtypes.html#str.find

1 Like

but if I was given the word “appple” it would not work.

I see that it works as expected, i.e. “ppl” is returned.

The find() method returns the first occurrence. Since there’s 3 “p” in your word, your code
word[x+1:y]
will return a segment that is the next “p” …up to before “e”
If you want starting from the last “p” , then try rfind() method. You may need to change some logic.