How to handle that a start and end in the wrong order?

Hi! Can someone help me understand what’s the +1 in start? thanks!

Hello @nahuelim,

return word[s+1 : end]

The +1 in the start positions you to the next character in the word string.

Here is a good explanation on string slicing: Python String Slicing - Learn By Example

I hope that helps.

My solution:
def substring_between_letters(word,start,end):

if start in word and end in word and word.find(start)!=word.find(end):

return word[word.find(start)+1:word.find(end)]

else: return word

My code appears to work except in cases where both start and end are the same character. How can I account for that in my code? I can’t seem to figure it out, even after looking at the replies in this thread so far. I’m quite new to coding so that doesn’t help.

Here is my code:

def substring_between_letters(word, start, end):
  word_start = word.find(start) + 1
  word_end = word.find(end)
  if word_end and word_start == -1:
    return word
  elif word_end < word_start:
    return word
  else:
    return word[word_start:word_end]

# Uncomment these function calls to test your function:
print(substring_between_letters("apple", "p", "e"))
# should print "pl" (this works)
print(substring_between_letters("apple", "p", "c"))
# should print "apple" (this also works)
print(substring_between_letters("mountain", "n", "n"))
#THE PROBLEM: should print "tai" but prints "mountain

Like a lot of similar methods .find only locates the first appearance of a matching substring- https://docs.python.org/3/library/stdtypes.html#str.find. If you check the docs you’ll see how to limit the range that .find searches through. Perhaps you could adapt your code to start the second search at an advanced position?

It’s worth noting that could change the behaviour for the regular match so consider whether you want to change the start only if the characters are the same or not. That’s probably up to you as you’re going beyond the instructions at this point :slightly_smiling_face:.

My solution:

def substring_between_letters(word, start, end):
  find_first = word.find(start)
  find_last = word.find(end)
  if (start != end) and ((start in word) and (end in word)):
    return word[find_first + 1:find_last]
  return word
1 Like

Nice attempt. We can go further end try something like this:

def substring_between_letters(word, start, end):
    pos_start = word.find(start)
    l_start = len(start)
    pos_end = word.find(end)
    if pos_start != -1 and pos_end > pos_start + l_start:
        return word[pos_start + l_start : pos_end]
    return word

print(substring_between_letters('abcdefg', 'ab', 'ef')) # cd
print(substring_between_letters('abcdefg', 'ef', 'bc')) # abcdefg
print(substring_between_letters('abcdefg', 'bc', 'cd')) # abcdefg
print(substring_between_letters('abcdefg', 'b', 'b')) # abcdefg

there is no limit to perfection