在字符串中找到最后一个子字符串?

时间:2019-03-17 19:10:47

标签: python

我正在尝试编写一个函数以查找字符串中的最后一个子字符串。我不需要任何其他代码的解决方案,我需要使用自己的过程来完成课程功课。

大多数测试都有效,尽管在aa中测试aaaaa时会失败。我理解为什么会这样,因为它是从仅剩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?

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

您的问题是这一行:

last_position = next_position + len(c)

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

我想你想要

last_position = next_position + 1

答案 2 :(得分:0)

这是因为您要使用找到的子字符串的长度来增加next_position,因此缺少最后一个匹配项。

@Service
public class CarListGrabber {

    @Autowired
    private NewCarRepository newCarRepository;

    // someOtherStuff
}

您还可以使用内置的python函数rindex(),该函数将从字符串末尾返回第一个索引计数

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
相关问题