如何计算字符串中子字符串的数量?

时间:2020-06-26 15:36:23

标签: python-3.x string substring

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

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

这给出的输出为

1

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

2

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

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

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))
相关问题