To solve this problem, we need to count the number of uppercase letters in a given string. The solution leverages Python's built-in string method isupper() to check if each character is uppercase and sums the results (since True is equivalent to 1 and False to 0 in Python).
Approach
- Iterate over each character: For every character in the input string, check if it is an uppercase letter using
isupper(). - Sum the uppercase characters: Since
isupper()returns a boolean value (Truefor uppercase,Falseotherwise), summing these values gives the count of uppercase letters.
Solution Code
def count_uppercase(s):
return sum(c.isupper() for c in s)
Explanation
c.isupper(): This method checks if a charactercis an uppercase letter (A-Z). It returnsTrueif it is, elseFalse.- Sum: The generator expression
(c.isupper() for c in s)produces a sequence of booleans. Summing these booleans (converted to integers 1 and 0) gives the total count of uppercase letters.
This approach is efficient with a time complexity of O(n), where n is the length of the string, as it processes each character exactly once. It handles edge cases like empty strings (returns 0) and non-letter characters (ignores them, as their isupper() result is False).
Example Usage:
- Input:
"Hello World!"→ Output:2(H and W are uppercase) - Input:
"PYTHON"→ Output:6(all characters are uppercase) - Input:
"123abc"→ Output:0(no uppercase letters)
This solution is concise, readable, and efficient for the problem requirements.

(免责声明:本文为本网站出于传播商业信息之目的进行转载发布,不代表本网站的观点及立场。本文所涉文、图、音视频等资料的一切权利和法律责任归材料提供方所有和承担。本网站对此资讯文字、图片等所有信息的真实性不作任何保证或承诺,亦不构成任何购买、投资等建议,据此操作者风险自担。) 本文为转载内容,授权事宜请联系原著作权人,如有侵权,请联系本网进行删除。