tanheg
tanheg

Reputation: 3

Can't figure out what is wrong with the code. Trying an alternative for string.find()

When I try to print the variables indA, indB or string it seems to work. Two letters and a word are inputted, and if the letters are present in the word, the characters between the two letters are printed.

def substring_between_letters(word, start, end):
  for index in range(len(word)):

    if word[index] == start:
      indA = index
      break
      return indA

    if word[index] == end:
      indB = index
      break
      return indB
      string = word[indA + 1 : indB]

    else:
      string = word

  return string 

Upvotes: 0

Views: 53

Answers (1)

Torin Kovach
Torin Kovach

Reputation: 56

This should work:

def substring_between_letters(word, start, end):
    hasA = False # Checks if start has already been found
    for index in range(len(word)):
        if word[index] == start:
            hasA = True
            aIndex = index
        if hasA and word[index] == end:
            bIndex = index
            return word[aIndex: bIndex + 1]
    return word # If substring could not be found

For instance:

>>> print(substring_between_letters("hello everyone!", "l", "e"))
lo e

The problems with your code include:

  • The break statements cause exiting of the loop before string can be defined. A better way to write this function actually forgoes break statements.
  • Returning the indA and indB causes the output of the function to just be a single integer.
  • The else statement is not needed in the for loop. Simply returning word at the end of the function and returning the correct string within the loop is cleaner and computationally faster.
  • The code as you wrote it has no catch to make sure end appears after start. If the end character appears after the start character, indA will not be defined and you will get an error.

Also, it looks like this code would give you the first instance where s substring begins with the character "start" and ends with the character "end." However, in str.find(sub, start, end), "start" and "end" define a substring of str in which to search for sub. If you were emulating str.find(), you would need four parameters: a string to search from (str), a substring to search for (sub), a starting integer (start) to define where in str to start searching, and an ending integer (end) to define where in str to stop searching.

Upvotes: 2

Related Questions