I am trying to figure out how I can count the uppercase letters in a string.
I have only been able to count lowercase letters:
def n_lower_chars(string):
return sum(map(str.islower, string))
Example of what I am trying to accomplish:
Type word: HeLLo
Capital Letters: 3
When I try to flip the function above, It produces errors:
def n_upper_chars(string):
return sum(map(str.isupper, string))
You can use
re
:This is not the fastest way, but I like how readable it is. Another way, without importing from string and with similar syntax, would be:
The (slightly) fastest method for this actually seems to be membership testing in a frozenset
Using
len
andfilter
:You can do this with
sum
, a generator expression, andstr.isupper
:See a demonstration below:
This works