我正在尝试编写一个函数来查找字符串中的最后一个子字符串。我不想要任何其他代码的解决方案,我需要使用我自己的类(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/