Count the uppercase letters in a string with Python

Stevenson picture Stevenson · Aug 8, 2013 · Viewed 78.5k times · Source

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))

Answer

user2555451 picture user2555451 · Aug 8, 2013

You can do this with sum, a generator expression, and str.isupper:

message = input("Type word: ")

print("Capital Letters: ", sum(1 for c in message if c.isupper()))

See a demonstration below:

>>> message = input("Type word: ")
Type word: aBcDeFg
>>> print("Capital Letters: ", sum(1 for c in message if c.isupper()))
Capital Letters:  3
>>>