0

这是我的功能的目标:

定义一个过程,find_last将两个字符串作为输入,一个搜索字符串和一个目标字符串,并返回搜索字符串中目标字符串出现的最后一个位置,或者-1如果没有出现目标字符串。

这是问题的链接。

到目前为止,这是我的功能:

def find_last(target, search):
    find = target.find(search, 0)

    if find != -1:
        targets = target.find(search, find)

        while targets != -1:
            find = find + 1
            targets = target.find(search, find)
        return find - 1
    else:
        return -1

代码返回我正在寻找的答案return find - 1,但我知道有更好的方法可以做到这一点。

任何帮助将不胜感激!

4

2 回答 2

9

你基本上实现了target.rfind(search).

于 2013-05-25T04:05:55.543 回答
6

你为什么不使用rfind

>>> d = "ball foo ball"
>>> f = "ball"
>>> d.rfind(f)
12

所以你的方法变成了 1 班轮 :)

def find_last(target, search):
    return target.rfind(search)

您可以返回target.rfind(search)并在调用方法中检查-1并适当处理。

忍不住要引用XKCD的这篇很棒的作品

看我在用 Python 飞行:P

于 2013-05-25T04:06:44.523 回答