Reputation: 21
I have this function matcher(word, first, last)
, where first will be the startswith(), and last will be endswith(). Word is obviously, the word I'm passing as argument.
It returns substrings from the word that has first
as the first letter, and last
as the last letter. For example,
matcher("apple", "a", "p")
>>> "app", "ap"
Is it possible to do it using the startswith() and endswith() built-in function? How should I approach this?
Upvotes: 1
Views: 803
Reputation: 27577
You could implement the str.startswith
method and the str.endswith
method into a nested for
loop:
def matcher(word, first, last):
length = len(word)
for i in range(length):
for j in range(i + 1, length + 1):
sub = word[i:j]
if sub.startswith(first) and sub.endswith(last):
print(sub)
matcher("apple", 'a', 'p')
Output:
ap
app
Upvotes: 1
Reputation: 71
Here is the logic for how I would do it:
This way you run the function once for every instance of the start letter.
Upvotes: 0