pythonstringlistcounter

Counting Substrings from a List, inside a String


I want to have a list of substrings look for inside of a string, and to receive the count of however many times a substring appears in that string.

list = ['one', 'two', 'three']
str = "one one two four five six"
count = str.count(list)

So in this example, count should be 3. However, .count() can't read strings from a list for some reason, so I'm not sure how to work around that.


Solution

  • One way is to use sum with a generator expression and utilizing set for O(1) lookup. str.split() splits your string into a list, separating by whitespace.

    str_set = {'one', 'two', 'three'}
    x = 'one one two four five six'
    
    count = sum(i in str_set for i in x.split())
    
    print(count)  # 3
    

    The reason this works is bool is a subclass of int, so we can sum True elements as if they are integers.

    Note you have a list and string, no tuple involved. In addition, do not name variables after classes (e.g. list, str, set).