确定子串在Python中的字符串中相邻出现的次数

时间:2016-11-04 12:40:51

标签: python string substring

我想计算一个子串在字符串中“相邻”出现的次数, 例如,给定字符串“8448442844”和子字符串“844”,我想要结果“2”。 我知道string.count(substring)函数,在这个例子中,使用这个函数,我会得到结果“3”。但我希望结果为“2”。如何提前感谢,我怎样才能实现目标。

4 个答案:

答案 0 :(得分:1)

这适用于任何相邻的子字符串:

type = 13

还可以使用a = "8448442844" sol, sub = 0, "844" for i in range(1, a.count(sub)+1): if a.count(str(sub*i)): sol = i else: break print (sol) # 2 Comprehension转换为单行:

sum

答案 1 :(得分:0)

使用str.count

>>> nStr = '000123000123'

>>> nStr.count('123')

2

或使用类似的东西

nStr = '000123000123'
pattern = '123'
count =0
flag=True
start=0
while flag:
    a = nStr.find(pattern,start)  # find() returns -1 if the word is not found, 
                                  #start i the starting index from the search starts(default value is 0)
    if a==-1:          #if pattern not found set flag to False
        flag=False
    else:               # if word is found increase count and set starting index to a+1
        count+=1        
        start=a+1
print(count)

答案 2 :(得分:0)

你可以这样尝试。也许把它放在def中。它工作得很好

import string

s = "8448442844"
sub = "844"
max_sub = sub
count = 0

while string.find(s, max_sub) != -1:
    max_sub = max_sub + sub
    count +=1

print count

答案 3 :(得分:0)

您可以使用str.splititertools.groupbymax来获取结果:

In [1]: import itertools

In [2]: "8448442844".split("844")
Out[2]: ['', '', '2', '']

In [3]: [len(list(lst)) for key, lst in itertools.groupby("8448442844".split("844")) if key == ""]
Out[3]: [2, 1]

In [4]: max([len(list(lst)) for key, lst in itertools.groupby("8448442844".split("844")) if key == ""])
Out[4]: 2