下面是我的代码:
def count_substring(string, sub_string):
counter = 0
for x in range(0,len(string)):
if string[x]+string[x+1]+string[x+2] == sub_string:
counter +=1
return counter
运行代码时,它会引发错误-“ IndexError:字符串索引超出范围” 请帮助我理解我的代码和解决方案的问题。 我是Python的初学者。请像我5岁时向我解释一下。
答案 0 :(得分:1)
您不能简单地将str.count
用于非重叠匹配:
str.count(substring, [start_index], [end_index])
full_str = 'Test for substring, check for word check'
sub_str = 'check'
print(full_str.count(sub_str))
返回2
如果您的子字符串匹配项重叠,则可以尝试re.findall
且前瞻性为正:
import re
full_str = 'bobob'
sub_str = 'bob'
print(len(re.findall('(?='+sub_str+')',full_str)))
如果您获得了新的regex.findall
模块,并且希望如此计算,请尝试使用overlapping
中的re.findall
参数并将其设置为true
:>
import regex as re
full_str = 'bobob'
sub_str = 'bob'
print(len(re.findall(sub_str, full_str, overlapped=True)))
两个选项都将返回:2
答案 1 :(得分:0)
您不能只使用count
吗?它使用更少的代码。参见JvdV的答案。另外,顺便说一下,这就是我的方法:
def count_substring(string, substring)
print(string.count(substring))
这大大简化了代码,您也可以完全摆脱该功能,然后执行以下操作:
print(string.count(substring)) # by the way you have to define string and substring first
如果要包括重叠的字符串,请执行以下操作:
def count(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
答案 2 :(得分:0)
字符串为此目的具有内置方法count
。
string = 'This is the way to do it.'
string.count('is')
Output: 2