Python | Case Counter in String

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output :

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

 

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().

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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']))

chevron_right


Output :

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : nidhi_biet

Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.