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

我试图计算出一个字符串在一个字符串中出现了多少次,例如:

nStr = '000123000123'

假设我要找的字符串是123。显然,它在 nStr 中出现了两次,但是我在将这个逻辑实现到 Python 中时遇到了麻烦。我现在得到的是:

pattern = '123'
count = a = 0
while pattern in nStr[a:]:
a = nStr[a:].find(pattern)+1
count += 1
return count

它应该返回的答案是2。此刻我陷入了一个无限循环。

我刚刚意识到计数是一个更好的方法,但出于好奇,有没有人看到一个类似于我已经得到的方法?

118881 次浏览

使用 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)
import re


pattern = '123'


n =re.findall(pattern, string)

我们可以说子字符串‘ pattern’在‘ string’中出现 len (n)次。

这里显示的 count()和其他方法的问题在于重叠子字符串的情况。

例如: "aaaaaa".count("aaa")返回2

如果你想让它返回4[ (aaa)aaa, a(aaa)aa, aa(aaa)a, aaa(aaa)] ,你可以这样做:

def count_substrings(string, substring):
string_size = len(string)
substring_size = len(substring)
count = 0
for i in xrange(0,string_size-substring_size+1):
if string[i:i+substring_size] == substring:
count+=1
return count


count_substrings("aaaaaa", "aaa")
# 4

不确定是否有更有效的方法来做到这一点,但我希望这能澄清 count()是如何工作的。

Count (substring)在重叠的情况下没有用。

我的方法是:

def count_substring(string, sub_string):


length = len(string)
counter = 0
for i in range(length):
for j in range(length):
if string[i:j+1] == sub_string:
counter +=1
return counter

你不能在每个循环中改变 a,你应该写:

a += nStr[a:].find(pattern)+1

而不是:

a = nStr[a:].find(pattern)+1
def count_substring(string, substring):
c=0
l=len(sub_string)
for i in range(len(string)):
if string [i:i+l]==sub_string:
c=c+1
return c
string=input().strip()
sub_string=input().strip()


count= count_substring(string,sub_string)
print(count)

正如@Jo ão Pesce 和@gaurav 所提到的,count()在子字符串重叠的情况下是没有用的,试试这个..。

def count_substring(string, sub_string):
c=0
for i in range(len(string)):
if(string[i:i+len(sub_string)]==sub_string):
c = c+1
return c
def countOccurance(str,pat):
count=0
wordList=str.split()
for word in wordList:
if pat in word:
count+=1
return count

如果您正在搜索如何解决这个重叠案例的问题。

s = 'azcbobobegghaklbob'
str = 'bob'
results = 0
sub_len = len(str)
for i in range(len(s)):
if s[i:i+sub_len] == str:
results += 1
print (results)

将导致3因为: [ azc (bob) oBegghaklbob ][ azcbo (bob) egghaklbob ][ azcboboBegghakl (bob)]

我是新来的,但我觉得这是个好办法,也许吧?

def count_substring(str, sub_str):
count = 0
for i, c in enumerate(str):
if sub_str == str[i:i+2]:
count += 1
return count

通常我用枚举来解决这类问题:

def count_substring(string, sub_string):
count = 0
for i, j in enumerate(string):
if sub_string in string[i:i+3]:
count = count + 1
return count

Def count (sub _ string,string) :

count = 0
ind = string.find(sub_string)


while True:
if ind > -1:
count += 1
ind = string.find(sub_string,ind + 1)
else:
break
return count
def count_substring(string, sub_string):
count = 0
len_sub = len(sub_string)
for i in range(0,len(string)):
if(string[i:i+len_sub] == sub_string):
count+=1
return count