garlic cheese
garlic cheese

Reputation: 21

How to check for strings that starts with, and ends with my parameters

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

Answers (2)

Red
Red

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

Rumaisa Habib
Rumaisa Habib

Reputation: 71

Here is the logic for how I would do it:

  1. Create a list to store these substrings
  2. Traverse the string till you find the first instance of the start letter
  3. Keep storing letters from here in a result string till you come across the end letter, at which point append this substring to the list and go on. Do not reset the result string for there may be longer strings.
  4. If you come across the start letter again, call the matcher function again, but only on the remaining letters (recursive). Whatever it returns, merge with your current list.
  5. When you have traversed the entire string, return the list

This way you run the function once for every instance of the start letter.

Upvotes: 0

Related Questions