【问题标题】:How to count the number of substrings in a string?如何计算字符串中子字符串的数量?
【发布时间】:2020-06-26 15:36:23
【问题描述】:

我想找出一个字符串中某个特定子字符串出现的次数。

string="abcbcbcb"
sub_str="cbc"
c=string.count(sub_str)
print(c)

这给出了输出

1

这是字符串中子字符串不重叠出现的次数。 但我也想计算重叠的字符串。因此,期望的输出是:

2

【问题讨论】:

标签: python-3.x string substring


【解决方案1】:

你可以使用正则表达式,使用模块“re”

print len(re.findall('(?=cbc)','abcbcbcb'))

【讨论】:

  • 这显示错误。但是在改进后它可以工作,谢谢!@Sergey Chinkov
【解决方案2】:

没有可用于重叠计数的标准函数。您可以编写自定义函数。

def count_occ(string, substr):
   cnt = 0
   pos = 0
   while(True):
       pos = string.find(substr , pos)
       if pos > -1:
           cnt += 1
           pos += 1
       else:
           break
   return cnt


string="abcbcbcb"
sub_str="cbc"
print(count_occ(string,sub_str))

【讨论】:

    猜你喜欢
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    • 2018-08-23
    • 2023-04-06
    • 2016-05-24
    • 2023-03-28
    • 1970-01-01
    相关资源
    最近更新 更多