具有重叠现象的字符串计数计算给定字符串出现的次数(包括python中的重叠)的最佳方法是什么?这是最明显的方式吗?def function(string, str_to_search_for):
count = 0
for x in xrange(len(string) - len(str_to_search_for) + 1):
if string[x:x+len(str_to_search_for)] == str_to_search_for:
count += 1
return count
function('1011101111','11')returns 5?还是说蟒蛇有更好的方法?
3 回答
慕容708150
TA贡献1831条经验 获得超4个赞
def occurrences(string, sub): count = start = 0 while True: start = string.find(sub, start) + 1 if start > 0: count+=1 else: return count
慕丝7291255
TA贡献1859条经验 获得超6个赞
>>> import re>>> text = '1011101111'>>> len(re.findall('(?=11)', text))5
>>> sum(1 for _ in re.finditer('(?=11)', text))5
re.escape
>>> def occurrences(text, sub): return len(re.findall('(?={0})'.format(re.escape(sub)), text))>>> occurrences(text, '11')5
HUWWW
TA贡献1874条经验 获得超12个赞
import regex as redef count_overlapping(text, search_for): return len(re.findall(search_for, text, overlapped=True))count_overlapping('1011101111','11') # 5
添加回答
举报
0/150
提交
取消