简体   繁体   English

在python中查找字符串中子字符串的出现次数

[英]to find number of occurrences of a substring in a string in python

question:In this challenge, the user enters a string and a substring.问题:在这个挑战中,用户输入一个字符串和一个子字符串。 You have to print the number of times that the substring occurs in the given string.您必须打印子字符串在给定字符串中出现的次数。 String traversal will take place from left to right, not from right to left.字符串遍历将从左到右进行,而不是从右到左。 NOTE: String letters are case-sensitive.注意:字符串字母区分大小写。

Sample Input样本输入

ABCDCDC CDC ABCDCCDC

Sample Output 2样本输出 2

This is my solution but i am not getting the correct output(i am getting 1 as output).这是我的解决方案,但我没有得到正确的输出(我得到 1 作为输出)。 What is the reason?是什么原因?

def count_subtring(string, sub_string):  
    len_string = int(len(string))
    len_substring = int(len(sub_string))
    l = len_string - len_substring + 1
    n = 0
    for i in range (l):
        if string[i:i + len_substring] == sub_string:
            n =+ 1
    return n

if __name__ == '__main__':
    string = input().strip()
    sub_string = input().strip()
    
    count = count_substring(string, sub_string)
    print(count)

and i found a solution but i am unable to understand it and i want a explanation for the below code我找到了一个解决方案,但我无法理解它,我想解释一下下面的代码

def count_substring(string, sub_string):
    count=0
    for i in range(len(string)):
        for j in range(len(sub_string)):
            if string[i+j]==sub_string[j] and j==(len(sub_string)-1):
                count=count+1  
            if string[i+j]!=sub_string[j]:
                break  
        if i==len(string)-len(sub_string):
            break            
    return count


if __name__ == '__main__':
    string = input().strip()
    sub_string = input().strip()
    
    count = count_substring(string, sub_string)
    print(count)

thanks谢谢

You are assigning n with +1 when you find a match instead of adding 1 to it ( n += 1 ).当您找到匹配项而不是向其添加 1 ( n += 1 ) 时,您正在为n分配+1

n =+ 1 is the same as n = +1 or n = 1 . n =+ 1n = +1n = 1相同。

So the result will never be greater than 1.所以结果永远不会大于 1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM