【问题标题】:Find how many times string appears in another python查找字符串在另一个python中出现的次数
【发布时间】:2022-01-01 08:33:59
【问题描述】:

python 中有没有一种方法可以检查一个字符串在另一个字符串中出现的次数? 例如

a="1ab1"
new_string="1ab1ab1ab1"

我应该得到 3,但我用 str.count() 得到了 2

谢谢

【问题讨论】:

标签: python string methods


【解决方案1】:

这是一个计算字符串中重叠子串数量的函数:

def getSubstringCount(s1, s2):
    pos = 0
    count = 0
    while pos < len(s1):
        pos = s1.find(s2, pos)
        if pos == -1:
            break
        else:
            count += 1
            pos += 1
    return count

a="1ab1"
new_string="1ab1ab1ab1"
cnt = new_string.count(a)
print(cnt)

输出:3

【讨论】:

  • 如果是 string="1ab1ab1ab1"a="1ab1" 我应该得到 3 但我得到了 2
猜你喜欢
  • 2013-11-19
  • 1970-01-01
  • 2015-10-08
  • 1970-01-01
  • 2017-12-17
  • 2011-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多