python - 在字符串中查找最后一个子字符串?

标签 python

我正在尝试编写一个函数来查找字符串中的最后一个子字符串。我不想要任何其他代码的解决方案,我需要使用我自己的类(class)作业程序来解决。

大多数测试都有效,尽管在 aaaaa 中测试 aa 时它失败了。我明白为什么,因为它从只剩下 a 的位置开始,但我该如何解决这个问题?

def find_last(s, c):
    last_position = 0
    result = -1

    while True:
        next_position = s.find(c, last_position)
        if next_position == -1:
            break
        result = next_position
        last_position = next_position + len(c)

    return result

print(find_last("aaaaa", "aa")) # should output 3 but doesn't?

最佳答案

如果你被允许使用内置函数,你可以这样做:

idx = s[::-1].find(c[::-1])
return len(s) - (idx + len(c)) if idx >= 0 else -1

关于python - 在字符串中查找最后一个子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55210878/

相关文章:

Python Twisted 多客户端

python - Pandas 数据框从窄到宽,数据透视表没有聚合

python - 如何使用 oauth2 为网站构建 Python 爬虫

python - 如何使 Django 表单字段仅包含字母数字字符

python - 如何根据按钮点击无条件重新运行python程序?

python - 强制 celery 使用 json 代替 pickle

python - 如何在 Flask 中引用多个模型?

python - 文件没有缓冲接口(interface)

python - 使用列表/元组/等。从键入与直接将类型引用为列表/元组/等

python - "if in"和 "if or if in"之间的差异;寻找解释