Count the uppercase letters in a string with Python

前端 未结 8 1973
佛祖请我去吃肉
佛祖请我去吃肉 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:48

    This works

    s = raw_input().strip()
    count = 1
    for i in s:
        if i.isupper():
            count = count + 1
    print count
    
    0 讨论(0)
  • 2021-01-01 10:50
    from string import ascii_uppercase
    count = len([letter for letter in instring if letter in ascii_uppercase])
    

    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:

    count = len([letter for letter in instring if letter.isupper()])
    
    0 讨论(0)
提交回复
热议问题