如何计算给定子字符串在Python字符串中出现的次数?
例如:
>>> 'foo bar foo'.numberOfOccurrences('foo')
2
若要获取子字符串的索引,请参见如何查找子字符串的所有出现?。
如何计算给定子字符串在Python字符串中出现的次数?
例如:
>>> 'foo bar foo'.numberOfOccurrences('foo')
2
若要获取子字符串的索引,请参见如何查找子字符串的所有出现?。
当前回答
def count_substring(string, sub_string):
inc = 0
for i in range(0, len(string)):
slice_object = slice(i,len(sub_string)+i)
count = len(string[slice_object])
if(count == len(sub_string)):
if(sub_string == string[slice_object]):
inc = inc + 1
return inc
if __name__ == '__main__':
string = input().strip()
sub_string = input().strip()
count = count_substring(string, sub_string)
print(count)
其他回答
你可以用两种方法计算频率:
使用str中的count(): a.count (b) 或者,你可以用: len (a.split (b)) 1
其中a是字符串,b是要计算频率的子字符串。
如果你想数整个字符串,这是可行的。
stri_count="If you're looking to count the whole string this can works"
print(len(stri_count))
使用Python 3.8中引入的赋值操作符,我们可以编写一个简短的函数,在循环中使用str.find()来查找字符串中目标子字符串的重叠实例。已经有一些其他的解决方案使用相同的方法,但这个更短,更快。
赋值表达式不仅用于在last-found实例之后的字符处开始下一个查找操作,还为while循环提供了终端表达式。Str.find()如果没有找到子字符串,则返回-1,在此基础上加上1将得到0,这是false,因此在没有找到更多匹配时退出循环。
# count overlapping occurrences of a substring in a string
def count_overlapping(haystack, needle, start=0, count=0):
while start := haystack.find(needle, start) + 1:
count += 1
return count
print(count_overlapping("moomoooo", "oo")) # 4
为了进一步优化性能,我们可以查阅草堆。在循环外找到一次,并将其存储在一个局部变量中。这将是更快时,有超过一对夫妇的比赛。
# count overlapping occurrences of a substring in a string
def count_overlapping(haystack, needle, start=0, count=0):
haystack_find = haystack.find
while start := haystack_find(needle, start) + 1:
count += 1
return count
def count_substring(string, sub_string):
k=len(string)
m=len(sub_string)
i=0
l=0
count=0
while l<k:
if string[l:l+m]==sub_string:
count=count+1
l=l+1
return count
if __name__ == '__main__':
string = input().strip()
sub_string = input().strip()
count = count_substring(string, sub_string)
print(count)
如果你想知道任何字符串中子字符串的计数;请使用以下代码。 代码很容易理解,这就是我跳过注释的原因。:)
string=raw_input()
sub_string=raw_input()
start=0
answer=0
length=len(string)
index=string.find(sub_string,start,length)
while index<>-1:
start=index+1
answer=answer+1
index=string.find(sub_string,start,length)
print answer