How to Count uppercase letter in a string Python

In this post, we will learn How to Count uppercase letters in a string Python with an example. The python isupper() method is used to check if the character is upper case and returns a Boolean value as result. If the character is the upper case then it returns True and else returns False. We will use regular expression, list comprehension, and sum() function to find upper case letters.

1. Count uppercase characters in a string Python


To find the count of uppercase letters in a given string. We have iterated over each character of the string by using generator expression. When the upper case character is found, pass it to the sum function and after iteration is over, the sum function will return the count of all upper case letters in the string.

strText = 'Welcome to DEVENUM.COM';
UpperCase_count = sum(1 for item in strText if item.isupper())
print('Upper case letter in String :',UpperCase_count)

Output

Upper case letter in String :11

2. Count uppercase characters in a string Python Using Regex


In this example, We are using the Regular expression ‘[A-Z]+’ to find the uppercase letter in a string and len() function to count a number of upper case letters. Let us understand code and output.

import re
myStr = "Welcome to DEVENUM.COM"
pattern =  '[A-Z]'
print('Uppercase Letter in string:',len(re.findall(pattern, myStr)))


Output

Uppercase Letter in string: 11

3. List comprehension to Count uppercase characters in a string


In this example, we have used list comprehension to Count uppercase characters in a string. We are iterating over the list and checking if a character in a string is uppercase using the .isupper() and len() methods that returns the count of uppercase in the string.

import re
myStr = "Welcome to DEVENUM.COM"
UpperCase_count  = len([item for item in myStr if item.isupper()])
print('Uppercase Letter in string:',UpperCase_count)

Output

Uppercase Letter in string: 11