使用Python计算字符串中的大写字母

问题描述 投票:19回答:6

我试图找出如何计算字符串中的大写字母。

我只能计算小写字母:

def n_lower_chars(string):
    return sum(map(str.islower, string))

我想要完成的例子:

Type word: HeLLo                                        
Capital Letters: 3

当我尝试翻转上面的函数时,它会产生错误:

def n_upper_chars(string):
    return sum(map(str.isupper, string))
python string python-3.x count uppercase
6个回答
40
投票

你可以用sumgenerator expressionstr.isupper做到这一点:

message = input("Type word: ")

print("Capital Letters: ", sum(1 for c in message if c.isupper()))

请参阅下面的演示:

>>> message = input("Type word: ")
Type word: aBcDeFg
>>> print("Capital Letters: ", sum(1 for c in message if c.isupper()))
Capital Letters:  3
>>>

7
投票

使用lenfilter

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

4
投票

你可以使用re

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

5


2
投票
from string import ascii_uppercase
count = len([letter for letter in instring if letter in ascii_uppercase])

这不是最快的方式,但我喜欢它的可读性。另一种方式,没有从字符串和类似的语法导入,将是:

count = len([letter for letter in instring if letter.isupper()])

1
投票

这有效

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

0
投票

(稍微)最快的方法实际上似乎是冻结集中的成员资格测试

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
© www.soinside.com 2019 - 2024. All rights reserved.