Count number of occurrences of a given substring in a string

后端 未结 30 1638
不思量自难忘°
不思量自难忘° 2020-11-22 13:58

How can I count the number of times a given substring is present within a string in Python?

For example:

>>> \'foo bar foo\'.numberOfOccurre         


        
相关标签:
30条回答
  • 2020-11-22 14:49
    s = input('enter the main string: ')
    p=input('enter the substring: ')
    l=[]
    for i in range(len(s)):
        l.append(s[i:i+len(p)])
    print(l.count(p))
    
    0 讨论(0)
  • 2020-11-22 14:50
    my_string = """Strings are amongst the most popular data types in Python. 
                   We can create the strings by enclosing characters in quotes.
                   Python treats single quotes the same as double quotes."""
    
    Count = my_string.lower().strip("\n").split(" ").count("string")
    Count = my_string.lower().strip("\n").split(" ").count("strings")
    print("The number of occurance of word String is : " , Count)
    print("The number of occurance of word Strings is : " , Count)
    
    0 讨论(0)
  • 2020-11-22 14:50

    Risking a downvote because 2+ others have already provided this solution. I even upvoted one of them. But mine is probably the easiest for newbies to understand.

    def count_substring(string, sub_string):
        slen  = len(string)
        sslen = len(sub_string)
        range_s = slen - sslen + 1
        count = 0
        for i in range(range_s):
            if (string[i:i+sslen] == sub_string):
                count += 1
        return count
    
    0 讨论(0)
  • 2020-11-22 14:51

    Scenario 1: Occurrence of a word in a sentence. eg: str1 = "This is an example and is easy". The occurrence of the word "is". lets str2 = "is"

    count = str1.count(str2)
    

    Scenario 2 : Occurrence of pattern in a sentence.

    string = "ABCDCDC"
    substring = "CDC"
    
    def count_substring(string,sub_string):
        len1 = len(string)
        len2 = len(sub_string)
        j =0
        counter = 0
        while(j < len1):
            if(string[j] == sub_string[0]):
                if(string[j:j+len2] == sub_string):
                    counter += 1
            j += 1
    
        return counter
    

    Thanks!

    0 讨论(0)
  • 2020-11-22 14:52

    The question isn't very clear, but I'll answer what you are, on the surface, asking.

    A string S, which is L characters long, and where S[1] is the first character of the string and S[L] is the last character, has the following substrings:

    • The null string ''. There is one of these.
    • For every value A from 1 to L, for every value B from A to L, the string S[A]..S[B] (inclusive). There are L + L-1 + L-2 + ... 1 of these strings, for a total of 0.5*L*(L+1).
    • Note that the second item includes S[1]..S[L], i.e. the entire original string S.

    So, there are 0.5*L*(L+1) + 1 substrings within a string of length L. Render that expression in Python, and you have the number of substrings present within the string.

    0 讨论(0)
  • 2020-11-22 14:54

    How about a one-liner with a list comprehension? Technically its 93 characters long, spare me PEP-8 purism. The regex.findall answer is the most readable if its a high level piece of code. If you're building something low level and don't want dependencies, this one is pretty lean and mean. I'm giving the overlapping answer. Obviously just use count like the highest score answer if there isn't overlap.

    def count_substring(string, sub_string):
        return len([i for i in range(len(string)) if string[i:i+len(sub_string)] == sub_string])
    
    0 讨论(0)
提交回复
热议问题