【问题标题】:search string with find() method and returning every char after 2nd occurrence in string使用 find() 方法搜索字符串并在字符串中第二次出现后返回每个字符
【发布时间】:2017-11-02 18:08:11
【问题描述】:

这是我之前遇到的另一个 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!

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

提前谢谢你!

【问题讨论】:

  • @CoryKramer 我应该加入那个论坛还是你在给某人加标签?
  • 查看What topics can I ask about here? 的帮助主题。由于您有工作代码,并且正在寻求潜在的改进,因此在代码审查网站上提出这个问题更合适。

标签: python string find indices edx


【解决方案1】:

您可以轻松地使用str.split,方法是将maxsplit 参数作为2 传递,然后从split 中取出最后一项:

>>> "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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-04
    • 2019-10-23
    • 1970-01-01
    • 2019-06-23
    相关资源
    最近更新 更多