Python: Count uppercase characters in a string

This article will discuss different ways to count the number of uppercase characters in a string.

Table of Contents

Count uppercase characters in a python string using for-loop

We can iterate over a string character by character using a for loop and count number of uppercase characters in the string during iteration,

def count_upper_case_letters(str_obj):
    count = 0
    for elem in str_obj:
        if elem.isupper():
            count += 1
    return count

count = count_upper_case_letters('This is a Sample Text')

print(count)

Output:

3

Count uppercase characters in a python string using sum() function

We can iterate over all the characters in a string using generator expression. When an uppercase character is found during iteration, yield that to the sum() function. In the end sum() function will return the total number of uppercase characters in a string,

str_obj = 'This is a Sample Text'

count = sum(1 for elem in str_obj if elem.isupper())

print(count)

Output:

3

Count uppercase characters in a python string using regex

We can call the findall() method of the regex module in Python with a pattern that matches all the uppercase characters in the string. findall() will return a list of all matches in the string, which in our case will be the upper case characters. Then, by fetching that uppercase character list’s size, we can get a count of uppercase characters in the string. For example,

import re

str_obj = 'This is a Sample Text'

count = len(re.findall(r'[A-Z]',str_obj))

print(count)

Output:

3

Count uppercase characters in a python string using list comprehension

Using list comprehension, iterate over all the characters in a string, and create a list of only uppercase characters from the string. Then, by fetching that uppercase character list’s size, we can get a count of uppercase characters in the string. For example,

str_obj = 'This is a Sample Text'

count = len([elem for elem in str_obj if elem.isupper()])

print(count)

Output:

3

Summary

In this article, we discussed different ways to count upper case characters in a string.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top