Count the uppercase letters in a string with Pytho

2019-04-18 07:04发布

问题:

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

回答1:

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


回答2:

Using len and filter :

import string
value = "HeLLo Capital Letters"
len(filter(lambda x: x in string.uppercase, value))
>>> 5


回答3:

You can use re:

import re
string = "Not mAnY Capital Letters"
len(re.findall(r'[A-Z]',string))

5



回答4:

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


回答5:

This works

s = raw_input().strip()
count = 1
for i in s:
    if i.isupper():
        count = count + 1
print count


回答6:

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