Reputation: 3
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
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:
break
statements cause exiting of the loop before string
can be defined. A better way to write this function actually forgoes break
statements.word
at the end of the function and returning the correct string
within the loop is cleaner and computationally faster.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