Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | Convert string list into multiple cases
Next article icon

Python | Case Counter in String

Last Updated : 23 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
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



Next Article
Python | Convert string list into multiple cases
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

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 - Case Insensitive Strings Grouping
    Sometimes, we have a use case in which we need to perform the grouping of strings by various factors, like first letter or any other factor. These type of problems are typical to database queries and hence can occur in web development while programming. This article focuses on one such grouping by c
    4 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
  • Python - Bigrams Frequency in String
    Sometimes while working with Python Data, we can have problem in which we need to extract bigrams from string. This has application in NLP domains. But sometimes, we need to compute the frequency of unique bigram for data collection. The solution to this problem can be useful. Lets discuss certain w
    4 min read
  • Python - Filter Similar Case Strings
    Given the Strings list, the task is to write a Python program to filter all the strings which have a similar case, either upper or lower. Examples: Input : test_list = ["GFG", "Geeks", "best", "FOr", "all", "GEEKS"] Output : ['GFG', 'best', 'all', 'GEEKS'] Explanation : GFG is all uppercase, best is
    9 min read
  • Python | K Character Split String
    The problems and at the same time applications of list splitting is quite common while working with python strings. Some characters are usually tend to ignore in the use cases. But sometimes, we might not need to omit those characters but include them in our programming output. Let’s discuss certain
    4 min read
  • Check if string contains character - Python
    We are given a string and our task is to check if it contains a specific character, this can happen when validating input or searching for a pattern. For example, if we check whether 'e' is in the string 'hello', the output will be True. Using in Operatorin operator is the easiest way to check if a
    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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences