正在查找字符串中的最后一个子字符串?

2024-04-26 18:41:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图编写一个函数来查找字符串中的最后一个子字符串。我不想在任何其他代码的解决方案,我需要做它使用我自己的课程作业过程。你知道吗

尽管在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?

Tags: 函数字符串代码过程def作业positionresult
3条回答

如果允许使用内置函数,可以执行以下操作:

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

你的问题是这行:

last_position = next_position + len(c)

这是跳过潜在的匹配。实际上,代码只考虑匹配的第一、第三和第五个位置。正如您所说,正确答案来自于检查第四个位置(index==3)。但是您跳过了它,因为您每次都移动测试字符串的长度,而不是只向前移动一个字符。你知道吗

我想你想要:

last_position = next_position + 1

这是因为您正在用找到的子串的长度增加下一个\u位置,因此错过了最后一个匹配。你知道吗

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)
        last_position += 1

    return result

print(find_last("aaaaa", "aa")) # -> 3

您还可以使用内置的python函数^{},它将返回从字符串末尾开始的第一个索引计数

print("aaaaa".rindex("aa")) # -> 3

相关问题 更多 >