Count the uppercase letters in a string with Python

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

    The (slightly) fastest method for this actually seems to be membership testing in a frozenset

    import string
    message='FoObarFOOBARfoobarfooBArfoobAR'
    s_upper=frozenset(string.uppercase)
    
    %timeit sum(1 for c in message if c.isupper())
    >>> 100000 loops, best of 3: 5.75 us per loop
    
    %timeit sum(1 for c in message if c in s_upper)
    >>> 100000 loops, best of 3: 4.42 us per loop
    

提交回复
热议问题