Count the uppercase letters in a string with Python

蓝咒 提交于 2019-11-30 17:05:56

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

Using len and filter :

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

You can use re:

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

5

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

This works

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

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