2
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

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

2 Comments

but if i have a string "22222222", and target="", out put should be 9, not -1. but rfind does not put this scenario into consideration
@SpencerJosephs Ah, I see. I've edited the answer to make it return the length of the search string if the target is an empty string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.