Spencer Josephs
Spencer Josephs

Reputation: 45

comparing strings in python

def find_last(search, target):
    for index, character in reversed(list(enumerate(search))):
        if character in target:
            return index
        else:
            return -1

suppose search="aaaaa" and target="aa", output should=3, not 4. I am trying to get the last position where the two strings compare

Upvotes: 2

Views: 138

Answers (1)

Shashank
Shashank

Reputation: 13869

Currently what you're doing is comparing each character from the search string in reverse order and seeing if it's in target. If it is, you prematurely return the wrong index.

Instead, I would recommend using the str.rfind method:

>>> 'aaaaa'.rfind('aa')
3

str.rfind is basically the same thing as the str.index method except it searches for the first needle from the right of the haystack.

Edit: In order to treat empty needles as being present at the rightmost index, you can use the following return expression:

def find_last(search, target):
        return target and search.rfind(target) or len(search)

Upvotes: 3

Related Questions