使用Python计算字符串中的大写字母 [英] Count the uppercase letters in a string with Python

查看:647
本文介绍了使用Python计算字符串中的大写字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何计算字符串中的大写字母。

I am trying to figure out how I can count the uppercase letters in a string.

我只能算小写字母:

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

我尝试完成的示例:

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


推荐答案

您可以使用 sum 生成器表达式 str.isupper

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

请参见下面的演示:

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

这篇关于使用Python计算字符串中的大写字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆