TittyBoii69
TittyBoii69

Reputation: 31

Better way to count multiple elements in a string

def get_count(input_str):
    
    return input_str.count("a") + input_str.count("e") + input_str.count("i") + input_str.count("o") + input_str.count("u")

Upvotes: 2

Views: 103

Answers (3)

Jett Chen
Jett Chen

Reputation: 382

You can simplify this in two ways:

First:

def get_count(input_str, target_str='aeiou'):
    return sum(map(input_str.count,target_str))

You can also use collections.Counter

from collections import Counter
def get_count(input_str, target_str='aeiou'):
    cnt = Counter(input_str)
    return sum([cnt[chr] for chr in target_str])

Upvotes: 0

Tim Roberts
Tim Roberts

Reputation: 54955

You have two strings: one that is your target, and one that is your search set. You have to loop through one of them and search the other. Which way is better depends on the length of the strings.

Upvotes: 0

Synthaze
Synthaze

Reputation: 6090

s = "hi what's up by there?"

lookup = ["e", "i", "u"]

print([s.count(x) for x in lookup])

Output:

[2, 1, 1]

In a function:

def lookup_count(s, lookup):
    return [s.count(x) for x in lookup]

Upvotes: 1

Related Questions