Count the uppercase letters in a string with Pytho

2019-04-18 06:10发布

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

6条回答
我命由我不由天
2楼-- · 2019-04-18 06:48

You can use re:

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

5

查看更多
叛逆
3楼-- · 2019-04-18 06:52
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()])
查看更多
干净又极端
4楼-- · 2019-04-18 06:55

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
查看更多
不美不萌又怎样
5楼-- · 2019-04-18 06:56

Using len and filter :

import string
value = "HeLLo Capital Letters"
len(filter(lambda x: x in string.uppercase, value))
>>> 5
查看更多
倾城 Initia
6楼-- · 2019-04-18 06:57

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
>>>
查看更多
家丑人穷心不美
7楼-- · 2019-04-18 07:03

This works

s = raw_input().strip()
count = 1
for i in s:
    if i.isupper():
        count = count + 1
print count
查看更多
登录 后发表回答