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

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

问题描述

我想弄清楚如何计算字符串中的大写字母.

我只能数小写字母:

def n_lower_chars(string):返回总和(地图(str.islower,字符串))

我想要完成的示例:

输入词:HeLLo大写字母:3

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

def n_upper_chars(string):返回总和(地图(str.isupper,字符串))

解决方案

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

message = input("输入单词:")print("大写字母:", sum(1 for c in message if c.isupper()))

请看下面的演示:

<预><代码>>>>message = input("输入单词:")输入词:aBcDeFg>>>print("大写字母:", sum(1 for c in message if c.isupper()))大写字母:3>>>

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

解决方案

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

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

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