Count the uppercase letters in a string with Python

前端 未结 8 1987
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-01 10:25

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(st         


        
8条回答
  •  情歌与酒
    2021-01-01 10:47

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

提交回复
热议问题