使用find()方法搜索字符串,并在第2次出现后返回字符串中的每个字符

时间:2017-06-01 14:22:41

标签: python string find indices edx

这是我之前遇到的另一项edX练习:

他们让我创建一个名为“after_second”的函数,它接受两个函数 参数: 1.要搜索的字符串 2.搜索词。

功能:返回第一个字符串中的所有内容 第二次出现搜索词。

例如:    after_second(“1122334455321”,“3”) - > 4455321

搜索词“3”出现在索引4和5处。因此,这将返回从索引6到结尾的所有内容。

after_second(“heyyoheyhi!”,“嘿”) - >喜!

搜索词“hey”出现在索引0和5处。搜索词本身是三个字符。因此,这将返回从索引8到结尾的所有内容。

这是我的代码:

def after_second(searchString, searchTerm):
    finder = searchString.find(searchTerm)
    count = 0
    while not finder == -1:
        finder = searchString.find(searchTerm, finder + 1)
        count += 1
        if count == 1:
            return searchString[finder + len(searchTerm):]

print(after_second("1122334455321", "3")) #Sample problems by edX
print(after_second("heyyoheyhi!", "hey")) #Sample problems by edX

返回预期的正确答案:

4455321
hi!

我想知道是否有更好的方法来构建我制作的代码。它输出正确的答案,但我不相信这是最好的答案。

提前谢谢!

1 个答案:

答案 0 :(得分:3)

您可以通过将str.split参数传递为2,然后从拆分中获取最终项目,轻松使用maxsplit

>>> "1122334455321".split('3', 2)[-1]
'4455321'
>>> "heyyoheyhi!".split('hey', 2)[-1]
'hi!'

您的功能现在可以写成:

def after_second(search_string, search_term):
    return search_string.split(search_term, 2)[-1]