Count the uppercase letters in a string with Python

我与影子孤独终老i 提交于 2019-12-03 20:36:42

问题


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


来源:https://stackoverflow.com/questions/18129830/count-the-uppercase-letters-in-a-string-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!