Skip to content Skip to sidebar Skip to footer

Is It Possible To Use .count On Multiple Strings In One Command For Python?

I was wondering is it possible to count for multiple strings using the .count function? string = 'abcdefg' string.count('.' or '!') When I use the or command, it only gives me the

Solution 1:

Unfortunately, the built-in str.count function doesn't support doing counts of multiple characters in a single call. The other respondents both use multiple calls to str.count and make multiple passes over the data. I believe your question specified that you didn't want to split the calls.

If you aspire for a single-pass search in only one call, there are several other ways.

One way uses a regex such as len(re.findall(r'[ab]', s)) which counts the number of a or b characters in a single pass. You could even do this in a memory-efficient iterator form, sum(1 for _ in re.finditer(r'[ab]', s)).

Another way uses sets together with filter. For example, len(filter({'a', 'b'}.__contains__, s)) also counts the number of a or b characters in a single pass. You also do this one in a memory-efficient iterator form, sum(1 for _ in itertools.ifilter({'a', 'b'}.__contains__, s)).

>>> s = 'abracadabra'>>> re.findall(r'[ab]', s)
['a', 'b', 'a', 'a', 'a', 'b', 'a']
>>> filter({'a', 'b'}.__contains__, s)
'abaaaba'

Just for grins, there is one other way but it is a bit off-beat, len(s) - len(s.translate(None, 'ab')). This starts with the total string length and subtracts the length of a translated string where the a and b characters have been removed.

Side note: In Python 3, filter() has changed to return an iterator. So the new code would become len(list(filter({'a', 'b'}.__contains__, s))) and sum(1 for _ in filter({'a', 'b'}.__contains__, s)).

Solution 2:

You could use a counter: simple but may not be memory efficient.

string_ = "abcdefg"
from collections importCountercounter= Counter(string_)
sum_ = counter['.'] + counter['!']

You could also simply use a list comprehension with sum (better):

string_ = "abcdefg"sum_ = sum(1 for c in string_ if c in '.!' else 0)

Solution 3:

The or statement will select the . as is is not None and the method count will never see the exclamation mark. However, it would also not be able to handle two independent strings to count. So you need to do this separately.

string.count(".") + string.count("!")

Solution 4:

You can use sum method to get the total.

string = "abcdefg.a.!"print(sum(string.count(i) for i in '.!'))

Output:

3

Solution 5:

You could use:

string.replace("!",".").count(".")

From preformance point of view I don't expect any benefit here, since the string hast to be parsed twice. However if your main motivation is to count the the chars in a one-liner (e.g. myFunctionReturnsString().replace("!",".").count(".")), this might help

Post a Comment for "Is It Possible To Use .count On Multiple Strings In One Command For Python?"