Sindyr
Sindyr

Reputation: 1357

How to count members of a set in a string in Python?

I have a list of letters and letter clusters, like this:

['x', 'str', 'a', 'pr']

I have a string that I need to know how many total occurrences of any member of the list are in it:

stripe = 1, rope = 0,, rprpraxp = 4, etc

Now I can loop over the members of the list counting occurrences of each member and then total them, like this:

sublist = ['x', 'str', 'a', 'pr']
string = "rprpraxp"
inst = 0
for member in sublist:
    inst = inst + string.count(member)
print(inst)

However I am wondering if I am missing a shorter, simpler, more intuitive and more Pythonic way of counting the members of a set of items in another string, something like:

inst = string.multicount(['x', 'str', 'a', 'pr'])

Anything like this exist?

Thanks.

Upvotes: 6

Views: 8442

Answers (2)

scharette
scharette

Reputation: 10017

I would use map and sum:

sublist = ['x', 'str', 'a', 'pr']
string = "rprpraxp"
print(sum(map(string.count, sublist)))

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799580

>>> S = "rprpraxp"
>>> L = ['x', 'str', 'a', 'pr']
>>> sum(S.count(e) for e in L if e in S)
4

Upvotes: 0

Related Questions