Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 606
Sindyr Avatar asked Nov 03 '17 18:11

Sindyr


People also ask

How do you count characters in a set in Python?

Use the count() Function to Count the Number of a Characters Occuring in a String in Python. We can count the occurrence of a value in strings using the count() function. It will return how many times the value appears in the given string.

How do I count the number of repeated characters in a string in Python?

Step 1: Declare a String and store it in a variable. Step 2: Use 2 loops to find the duplicate characters. Outer loop will be used to select a character and initialize variable count to 1. Step 3: Inner loop will be used to compare the selected character with remaining characters of the string.


1 Answers

I would use map and sum:

sublist = ['x', 'str', 'a', 'pr']
string = "rprpraxp"
print(sum(map(string.count, sublist)))
like image 144
scharette Avatar answered Oct 12 '22 23:10

scharette