【问题标题】:In a string, how to find the index of the first character of the nth occurrence of a substring Python [duplicate]在字符串中,如何找到子字符串第n次出现的第一个字符的索引Python [重复]
【发布时间】:2021-07-29 20:02:36
【问题描述】:

假设我有一个很长的字符串longString 和一个更短的子字符串substring。我想在longString 中找到substringnth 出现的第一个字符的索引。换句话说,假设substring = "stackoverflow",我想在longString中找到"stackoverflow"的第n次出现,并找到substring的第一个字符的索引(即字母s)。

例子:

longString = "stackoverflow_is_stackoverflow_not_stackoverflow_even_though_stackoverflow"
substring = "stackoverflow"
n = 2

因此,在上面的示例中,s 在第二次出现"stackoverflow" 中的索引为 17。

我想找到一种高效且快速的方法。

【问题讨论】:

  • 请注意,搜索字符串可能与自身重叠,例如abcxyzabc,因此您需要决定如何计算 abcxyzabcxyzabcxyzabc 中的搜索,即忽略重叠部分,还是计算它?
  • @Tom Karzes 在我目前的情况下,我想忽略。

标签: python string indexing


【解决方案1】:

这是一个很短的方法:

def index_of_nth_occurrence(longstring, substring, n):
    return len(substring.join(longstring.split(substring)[:n]))
    

longstring = "stackoverflow_is_stackoverflow_not_stackoverflow_even_though_stackoverflow"
substring = "stackoverflow"
n = 2

print(index_of_nth_occurrence(longstring, substring, n)
# 17

这里的技巧是使用str.split() 查找子字符串的非重叠出现,然后将它们中的第一个n 连接回来,并检查总共有多少个字符。紧随其后的下一个字符将是子字符串第nth 次出现的第一个字符。


这可能比迭代/手动方法效率低,并且会忽略重叠匹配,但它既快速又简单。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-21
    • 2011-03-14
    • 2010-12-25
    • 2015-05-12
    • 2011-08-06
    • 2018-03-22
    • 1970-01-01
    相关资源
    最近更新 更多