如何计算给定子字符串在Python字符串中出现的次数?
例如:
>>> 'foo bar foo'.numberOfOccurrences('foo')
2
若要获取子字符串的索引,请参见如何查找子字符串的所有出现?。
如何计算给定子字符串在Python字符串中出现的次数?
例如:
>>> 'foo bar foo'.numberOfOccurrences('foo')
2
若要获取子字符串的索引,请参见如何查找子字符串的所有出现?。
当前回答
j = 0
while i < len(string):
sub_string_out = string[i:len(sub_string)+j]
if sub_string == sub_string_out:
count += 1
i += 1
j += 1
return count
其他回答
重叠出现:
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
import re
d = [m.start() for m in re.finditer(pattern, string)]
print(d)
这将查找子字符串在字符串中被找到的次数并显示索引。
string="abc"
mainstr="ncnabckjdjkabcxcxccccxcxcabc"
count=0
for i in range(0,len(mainstr)):
k=0
while(k<len(string)):
if(string[k]==mainstr[i+k]):
k+=1
else:
break
if(k==len(string)):
count+=1;
print(count)
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
根据你的真正意思,我提出以下解决方案:
你的意思是一个空格分隔子字符串的列表,并想知道所有子字符串中的子字符串位置编号是什么: S = 'sub1 sub2 sub3' s.split () .index(“sub2”) > > > 1 你的意思是子字符串在字符串中的char-position: s.find(“sub2”) > > > 5 你的意思是su-bstring的(非重叠)外观计数: s.count(“sub2”) > > > 1 s.count(“子”) > > > 3