如何计算给定子字符串在Python字符串中出现的次数?
例如:
>>> 'foo bar foo'.numberOfOccurrences('foo')
2
若要获取子字符串的索引,请参见如何查找子字符串的所有出现?。
如何计算给定子字符串在Python字符串中出现的次数?
例如:
>>> 'foo bar foo'.numberOfOccurrences('foo')
2
若要获取子字符串的索引,请参见如何查找子字符串的所有出现?。
当前回答
#counting occurence of a substring in another string (overlapping/non overlapping)
s = input('enter the main string: ')# e.g. 'bobazcbobobegbobobgbobobhaklpbobawanbobobobob'
p=input('enter the substring: ')# e.g. 'bob'
counter=0
c=0
for i in range(len(s)-len(p)+1):
for j in range(len(p)):
if s[i+j]==p[j]:
if c<len(p):
c=c+1
if c==len(p):
counter+=1
c=0
break
continue
else:
break
print('number of occurences of the substring in the main string is: ',counter)
其他回答
重叠出现:
def olpcount(string,pattern,case_sensitive=True):
if case_sensitive != True:
string = string.lower()
pattern = pattern.lower()
l = len(pattern)
ct = 0
for c in range(0,len(string)):
if string[c:c+l] == pattern:
ct += 1
return ct
test = 'my maaather lies over the oceaaan'
print test
print olpcount(test,'a')
print olpcount(test,'aa')
print olpcount(test,'aaa')
结果:
my maaather lies over the oceaaan
6
4
2
在给定字符串中查找重叠子字符串的最佳方法是使用正则表达式。使用ahead,它将使用正则表达式库的findall()找到所有重叠的匹配。这里,左边是子字符串,右边是要匹配的字符串。
>>> len(re.findall(r'(?=aa)', 'caaaab'))
3
下面的逻辑将适用于所有字符串和特殊字符
def cnt_substr(inp_str, sub_str):
inp_join_str = ''.join(inp_str.split())
sub_join_str = ''.join(sub_str.split())
return inp_join_str.count(sub_join_str)
print(cnt_substr("the sky is $blue and not greenthe sky is $blue and not green", "the sky"))
#counting occurence of a substring in another string (overlapping/non overlapping)
s = input('enter the main string: ')# e.g. 'bobazcbobobegbobobgbobobhaklpbobawanbobobobob'
p=input('enter the substring: ')# e.g. 'bob'
counter=0
c=0
for i in range(len(s)-len(p)+1):
for j in range(len(p)):
if s[i+j]==p[j]:
if c<len(p):
c=c+1
if c==len(p):
counter+=1
c=0
break
continue
else:
break
print('number of occurences of the substring in the main string is: ',counter)
s = 'arunununghhjj'
sb = 'nun'
results = 0
sub_len = len(sb)
for i in range(len(s)):
if s[i:i+sub_len] == sb:
results += 1
print results