Python | Case Counter in String
Last Updated :
23 Mar, 2023
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
test_str = "GFG is For GeeKs"
print ( "The original string is : " + test_str)
res_upper = sum ( map ( str .isupper, test_str))
res_lower = sum ( map ( str .islower, test_str))
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
from collections import Counter
test_str = "GFG is For GeeKs"
print ( "The original string is : " + test_str)
res = Counter( "upper" if ele.isupper() else "lower" if ele.islower()
else " " for ele in test_str)
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
test_str = "GFG is For GeeKs"
print ( "The original string is : " + test_str)
res_upper = 0
res_lower = 0
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
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
test_str = "GFG is For GeeKs"
print ( "The original string is : " + test_str)
res_upper = len (re.findall(r '[A-Z]' ,test_str))
res_lower = len (re.findall(r '[a-z]' ,test_str))
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 #5 : Without any builtin methods
Python3
test_str = "GFG is For GeeKs"
print ( "The original string is : " + test_str)
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
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
test_str = "GFG is For GeeKs"
print ( "The original string is : " + test_str)
res_upper = len ()
res_lower = len ()
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 :
- Import the defaultdict class from the collections module.
- Initialize a string test_str.
- Create an empty dictionary res_dict using the defaultdict class with the default value as int.
- Loop over each character ele in the test_str.
- If the character is a space, continue to the next iteration of the loop.
- Increment the count of the current character in res_dict.
- Print the count of each character in the string.
Python3
from collections import defaultdict
test_str = "GFG is For GeeKs"
print ( "The original string is : " + test_str)
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
print ( "The count of Upper case characters : " + str (res[ 'Upper Case' ]))
print ( "The count of Lower case characters : " + str (res[ 'Lower Case' ]))
|
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 - 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 occu
4 min read
Alternate cases in String - Python
The task of alternating the case of characters in a string in Python involves iterating through the string and conditionally modifying the case of each character based on its position. For example, given a string s = "geeksforgeeks", the goal is to change characters at even indices to uppercase and
3 min read
Python | Convert string list into multiple cases
Sometimes, while working with Python strings, we might have a problem in which we have list of strings and we wish to convert them into specified cases. This problem generally occurs in the cases in which the strings we receive are ill-cased. Let's discuss certain ways in which this task can be perf
4 min read
Python - Check for spaces in string
Sometimes, while working with strings in Python, we need to determine if a string contains any spaces. This is a simple problem where we need to check for the presence of space characters within the string. Let's discuss different methods to solve this problem. Using 'in' operator'in' operator is on
3 min read
Python - Specific case change in String List
While working with String lists, the problem of cases is common, but sometimes, we are concerned about changing cases in strings selectively. i.e. on the basis of another list. This can have applications in day-day programming. Let us discuss certain ways in which this task can be performed. Method
7 min read
Insert a number in string - Python
We are given a string and a number, and our task is to insert the number into the string. This can be useful when generating dynamic messages, formatting output, or constructing data strings. For example, if we have a number like 42 and a string like "The number is", then the output will be "The num
2 min read
Python - Least Frequent Character in String
The task is to find the least frequent character in a string, we count how many times each character appears and pick the one with the lowest count. Using collections.CounterThe most efficient way to do this is by using collections.Counter which counts character frequencies in one go and makes it ea
3 min read
Python - Check if string contains character
In Python, we can check if a string contains a character using several methods. in operator is the simplest and most commonly used way. If we need more control, methods like find(), index(), and count() can also be useful. Using in Operator in operator is the easiest way to check if a character exis
2 min read
Case-insensitive string comparison in Python
The goal here is to compare strings in a list without considering their case, meaning the comparison should ignore whether letters are uppercase or lowercase. For example, given the list ["hello", "HELLO", "HeLLo"], we want to check if all strings are equal, ignoring the case. Let's explore differen
2 min read
First N letters String Construction - Python
The task of constructing a string from the first N letters of a given string in Python involves extracting a specific portion of the string, starting from the beginning and including the first N characters. For example, if we have the string "GeeksForGeeks" and want to extract the first 5 characters
3 min read