The Wayback Machine - https://web.archive.org/web/20240709231133/https://www.geeksforgeeks.org/python-case-counter-in-string/
Open In App

Python | Case Counter in String

Last Updated : 23 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python String, we can have a problem in which we need to separate the lower and upper case count. This kind of operation can have its application in many domains. Let’s discuss certain ways in which this task can be done.

Method #1: Using map() + sum() + isupper() + islower() The combination of the above functions can be used to perform this task. In this, we separately extract the count using sum() and map() and respective inbuilt functions. 

Python3




# Python3 code to demonstrate working of
# Case Counter in String
# using map() + sum() + isupper + islower
 
# initializing string
test_str = "GFG is For GeeKs"
 
# printing original string
print("The original string is : " + test_str)
 
# Case Counter in String
# using map() + sum() + isupper + islower
res_upper = sum(map(str.isupper, test_str))
res_lower = sum(map(str.islower, test_str))
 
# printing result
print("The count of Upper case characters : " + str(res_upper))
print("The count of Lower case characters : " + str(res_lower))


Output : 

The original string is : GFG is For GeeKs
The count of Upper case characters : 6
The count of Lower case characters : 7

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #2: Using Counter() + isupper() + islower() The combinations of above methods can also be used to perform this particular task. In this, we perform the task of holding count using Counter(). 

Python3




# Python3 code to demonstrate working of
# Case Counter in String
# using Counter() + isupper() + islower()
from collections import Counter
 
# initializing string
test_str = "GFG is For GeeKs"
 
# printing original string
print("The original string is : " + test_str)
 
# Case Counter in String
# using Counter() + isupper() + islower()
res = Counter("upper" if ele.isupper() else "lower" if ele.islower()
              else " " for ele in test_str)
 
# printing result
print("The count of Upper case characters : " + str(res['upper']))
print("The count of Lower case characters : " + str(res['lower']))


Output : 

The original string is : GFG is For GeeKs
The count of Upper case characters : 6
The count of Lower case characters : 7

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #3: Using ord() function (ASCII Values)

Python3




# Python3 code to demonstrate working of
# Case Counter in String
# initializing string
test_str = "GFG is For GeeKs"
 
# printing original string
print("The original string is : " + test_str)
res_upper = 0
res_lower = 0
# Case Counter in String
for i in test_str:
    if(ord(i) >= ord('A') and ord(i) <= ord('Z')):
        res_upper += 1
    elif(ord(i) >= ord('a') and ord(i) <= ord('z')):
        res_lower += 1
# printing result
print("The count of Upper case characters : " + str(res_upper))
print("The count of Lower case characters : " + str(res_lower))


Output

The original string is : GFG is For GeeKs
The count of Upper case characters : 6
The count of Lower case characters : 7

Time Complexity: O(n)
Auxiliary Space: O(1)

Method #4: Using regex

Python3




import re
 
#initializing string
test_str = "GFG is For GeeKs"
 
#printing original string
print("The original string is : " + test_str)
 
#Case Counter in String
res_upper = len(re.findall(r'[A-Z]',test_str))
res_lower = len(re.findall(r'[a-z]',test_str))
 
#printing result
print("The count of Upper case characters : " + str(res_upper))
print("The count of Lower case characters : " + str(res_lower))
#this code is contributed by edula vinay kumar reddy


Output

The original string is : GFG is For GeeKs
The count of Upper case characters : 6
The count of Lower case characters : 7

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #5 : Without any builtin methods

Python3




# Python3 code to demonstrate working of
# Case Counter in String
 
# initializing string
test_str = "GFG is For GeeKs"
 
# printing original string
print("The original string is : " + test_str)
 
# Case Counter in String
res_upper = 0
res_lower = 0
la="abcdefghijklmnopqrstuvwxyz"
ua="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in test_str:
    if i in la:
        res_lower+=1
    elif i in ua:
        res_upper+=1
# printing result
print("The count of Upper case characters : " + str(res_upper))
print("The count of Lower case characters : " + str(res_lower))


Output

The original string is : GFG is For GeeKs
The count of Upper case characters : 6
The count of Lower case characters : 7

Time complexity: O(n), where n is the length of the input string, because it has to traverse the string once to count the number of upper and lower case characters. 
Auxiliary space: O(1), because it only needs to store the counts of upper and lower case characters, which are constant and don’t change with the size of the input.

Method 6: Using for loop

Python3




test_str = "GFG is For GeeKs"
upper_count = 0
lower_count = 0
 
for char in test_str:
    if char.isupper():
        upper_count += 1
    elif char.islower():
        lower_count += 1
 
print("The count of Upper case characters : " + str(upper_count))
print("The count of Lower case characters : " + str(lower_count))


Output

The count of Upper case characters : 6
The count of Lower case characters : 7

Time Complexity: O(n), where n is the length of test_str
Auxiliary Space: O(1)

Method #7: Using list comprehension

Python3




# Python3 code to demonstrate working of
# Case Counter in String
# using list comprehension
 
# initializing string
test_str = "GFG is For GeeKs"
 
# printing original string
print("The original string is : " + test_str)
 
# Case Counter in String
# using list comprehension
res_upper = len()
res_lower = len()
 
# printing result
print("The count of Upper case characters : " + str(res_upper))
print("The count of Lower case characters : " + str(res_lower))


Output

The original string is : GFG is For GeeKs
The count of Upper case characters : 6
The count of Lower case characters : 7

Time complexity: O(n), where n is the length of the string.
Auxiliary space: O(1), as we are only storing two integer variables.

Method #8:Using collections.defaultdict :

Algorithms :

  1. Import the defaultdict class from the collections module.
  2. Initialize a string test_str.
  3. Create an empty dictionary res_dict using the defaultdict class with the default value as int.
  4. Loop over each character ele in the test_str.
  5. If the character is a space, continue to the next iteration of the loop.
  6. Increment the count of the current character in res_dict.
  7. Print the count of each character in the string.

Python3




from collections import defaultdict
# initializing string
test_str = "GFG is For GeeKs"
# printing original string
print("The original string is : " + test_str)
# Case Counter in String
# using defaultdict() + isupper() + islower()
res = defaultdict(int)
for char in test_str:
    if char.isupper():
        res["Upper Case"] += 1
    elif char.islower():
        res["Lower Case"] += 1
    else:
        res["Space"] += 1
# printing result
print("The count of Upper case characters : " + str(res['Upper Case']))
print("The count of Lower case characters : " + str(res['Lower Case']))
 
#This code is contributed by Jyothi Pinjala.


Output

The original string is : GFG is For GeeKs
The count of Upper case characters : 6
The count of Lower case characters : 7

The time complexity :O(n) because it iterates through the string once and the operations inside the loop take constant time.
The space complexity: O(1) because the only additional data structure used is the defaultdict, which is a constant amount of space regardless of the length of the string



Similar Reads

Python - Counter.items(), Counter.keys() and Counter.values()
Counter class is a special type of object data-set provided with the collections module in Python3. Collections module provides the user with specialized container datatypes, thus, providing an alternative to Python’s general-purpose built-ins like dictionaries, lists and tuples. Counter is a sub-class that is used to count hashable objects. It imp
3 min read
Python - Case Insensitive string counter
Given a list of strings, find the frequency of strings case insensitive. Input : test_list = ["Gfg", "Best", "GFG", "is", "IS", "BEST"] Output : {'gfg': 2, 'best': 2, 'is': 2} Explanation : All occur twice. Input : test_list = ["Gfg", "gfg", "GFG"] Output : {'gfg': 3} Explanation : Only "gfg" 3 occurrences. Method 1: Using defaultdict() + lower() I
4 min read
Python program to convert camel case string to snake case
Given a string in camel case, write a Python program to convert the given string from camel case to snake case.Examples: Input : GeeksForGeeks Output : geeks_for_geeks Input : ThisIsInCamelCase Output : this_is_in_camel_case Let's see the different ways we can do this task. Method #1 : Naive ApproachThis is a naive implementation to convert camel c
4 min read
Python - Convert Snake Case String to Camel Case
Given a snake case string, convert to camel case. Input : test_str = 'geeksforgeeks_is_best_for_geeks' Output : geeksforgeeksIsBestForGeeks Explanation : String converted to Camel Case. Input : test_str = 'geeksforgeeks_best_for_geeks' Output : geeksforgeeksBestForGeeks Explanation : String converted to Camel Case. Method #1: Using split() + join()
4 min read
Python regex to find sequences of one upper case letter followed by lower case letters
Write a Python Program to find sequences of one upper case letter followed by lower case letters. If found, print 'Yes', otherwise 'No'. Examples: Input : GeeksOutput : YesInput : geeksforgeeksOutput : NoPython regex to find sequences of one upper case letter followed by lower case lettersUsing re.search() To check if the sequence of one upper case
2 min read
Python - Convert Snake case to Pascal case
Sometimes, while working with Python Strings, we have problem in which we need to perform a case conversion of String. This a very common problem. This can have application in many domains such as web development. Lets discuss certain ways in which this task can be performed. Input : geeks_for_geeks Output : GeeksforGeeks Input : left_index Output
7 min read
Python counter and dictionary intersection example (Make a string using deletion and rearrangement)
Given two strings, find if we can make first string from second by deleting some characters from second and rearranging remaining characters. Examples: Input : s1 = ABHISHEKsinGH : s2 = gfhfBHkooIHnfndSHEKsiAnG Output : Possible Input : s1 = Hello : s2 = dnaKfhelddf Output : Not Possible Input : s1 = GeeksforGeeks : s2 = rteksfoGrdsskGeggehes Outpu
2 min read
Using Counter() in Python to find minimum character removal to make two strings anagram
Given two strings in lowercase, the task is to make them Anagram. The only allowed operation is to remove a character from any string. Find minimum number of characters to be deleted to make both the strings anagram? If two strings contains same data set in any order then strings are called Anagrams. Examples: Input : str1 = "bcadeh" str2 = "hea" O
3 min read
Python dictionary, set and counter to check if frequencies can become same
Given a string which contains lower alphabetic characters, we need to remove at most one character from this string in such a way that frequency of each distinct character becomes same in the string. Examples: Input : str = “xyyz” Output : Yes We can remove character ’y’ from above string to make the frequency of each character same. Input : str =
2 min read
Dictionary and counter in Python to find winner of election
Given an array of names of candidates in an election. A candidate name in the array represents a vote cast to the candidate. Print the name of candidates received Max vote. If there is tie, print a lexicographically smaller name. Examples: Input : votes[] = {"john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "john", "johnny",
3 min read
Practice Tags :
three90RightbarBannerImg