Leafus
Leafus

Reputation: 15

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.

Upvotes: 1

Views: 527

Answers (3)

jpp
jpp

Reputation: 164843

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).

Upvotes: 3

Netwave
Netwave

Reputation: 42796

Use a generator expression and sum:

count = sum(1 for x in the_string.split(" ") if x in tup)

Upvotes: 0

modesitt
modesitt

Reputation: 7210

I think what you want is the following

count = sum([str.count(e) for e in tup))

Which sums the number of times any substring in the tup appears in str.

Also, your tuple is a list. To make it a tuple (immutable), use (

('one', 'two', 'three')

Also, you should use the variable name str_ (standard python convention) to avoid overloading the str object.

Upvotes: 0

Related Questions