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:
Similarity Metrics of Strings - Python
Next article icon

Python – Filter Similar Case Strings

Last Updated : 18 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 all lowercase.


Input : test_list = [“GFG”, “Geeks”, “best”] 
Output : [‘GFG’, ‘best’] 
Explanation : GFG is all uppercase, best is all lowercase.
 

Method #1 : Using islower() + isupper() + list comprehension

In this, we check for each string to be lower or upper case using islower() and isupper(), and list comprehension is used to iterate through strings.

Python3

# Python3 code to demonstrate working of
# Filter Similar Case Strings
# Using islower() + isupper() + list comprehension
 
# Initializing Matrix
test_list = ["GFG", "Geeks",
             "best", "FOr", "all", "GEEKS"]
 
# Printing original list
print("The original list is : " + str(test_list))
 
# Checking for cases via
# islower() and isupper()
res = [sub for sub in test_list if sub.islower() or sub.isupper()]
 
# Printing result
print("Strings with same case : " + str(res))
                      
                       

Output
The original list is : ['GFG', 'Geeks', 'best', 'FOr', 'all', 'GEEKS'] Strings with same case : ['GFG', 'best', 'all', 'GEEKS']

Method #2: Using islower() + isupper() + filter() + lambda

In this, we perform the task of filtering strings using filter() and lambda function. Rest all the functionality is similar to the above method.

Python3

# Python3 code to demonstrate working of
# Filter Similar Case Strings
# Using islower() + isupper() + filter() + lambda
 
# initializing Matrix
test_list = ["GFG", "Geeks", "best",
             "FOr", "all", "GEEKS"]
              
# printing original list
print("The original list is : " + str(test_list))
 
# islower() and isupper() used to check for cases
# filter() and lambda function used for filtering
res = list(filter(lambda sub : sub.islower() or sub.isupper(), test_list))
 
# printing result
print("Strings with same case : " + str(res))
                      
                       

Output
The original list is : ['GFG', 'Geeks', 'best', 'FOr', 'all', 'GEEKS'] Strings with same case : ['GFG', 'best', 'all', 'GEEKS']

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

Method 3: Using regex (Regular Expression)

Approach: Filter Similar Case Strings Using regex (Regular Expression) 

  1. Import the ‘re’ library.
  2. Create a list of strings named ‘test_list’ and print the original list ‘test_list’.
  3. Use a list comprehension to iterate through ‘test_list’ and filter out the strings which have all uppercase or all lowercase letters.
  4. Use re.match function to match the pattern of uppercase or lowercase in each string.
  5. The pattern ‘[A-Z]+’ matches one or more uppercase letters and the pattern ‘[a-z]+’ matches one or more lowercase letters.
  6. The ‘^’ sign indicates the start of the string, and the ‘$’ sign indicates the end of the string.
  7. Append the matched strings to the list ‘res’.
  8. Print the final filtered list ‘res’.

Python3

import re
 
test_list = ["GFG", "Geeks", "best", "FOr", "all", "GEEKS"]
print("The original list is : " + str(test_list))
 
# Using re.match to match the pattern of uppercase or lowercase
# The pattern '[A-Z]+' matches one or more uppercase letters
# The pattern '[a-z]+' matches one or more lowercase letters
res = [i for i in test_list if re.match(
    '^[A-Z]+$', i) or re.match('^[a-z]+$', i)]
 
print("Strings with same case : " + str(res))
                      
                       

Output
The original list is : ['GFG', 'Geeks', 'best', 'FOr', 'all', 'GEEKS'] Strings with same case : ['GFG', 'best', 'all', 'GEEKS']

Time complexity: O(NM)
The time complexity of the algorithm is O(n*m), where n is the number of strings in the list and m is the average length of each string. The regular expression pattern matching is a linear-time operation, but we need to perform it for each string in the list, so the overall time complexity is proportional to the number of strings and their length.

Auxiliary space complexity: O(K)
The auxiliary space complexity of the algorithm is O(k), where k is the number of strings that match the regular expression pattern. We create a new list ‘res’ to store the filtered strings. The maximum size of this list is k, so the space complexity is proportional to the number of matched strings. The original list ‘test_list’ is not modified, so its space complexity is not considered.

Method #4: Using Numpy

Algorithm:

  1. Create a list of strings called test_list.
  2. Convert the list into a NumPy array called arr.
  3. Use NumPy’s np.char.islower() and np.char.isupper() functions to create two boolean arrays of the same shape as arr. The first array indicates for whether each element of arr is lowercase, and the second array indicates whether each element is uppercase.
  4. Use logical OR to combine the two boolean arrays element-wise, creating a third boolean array that is also of the same shape as arr.
  5. Use the resulting boolean array to index arr, selecting only the elements that have either all lowercase or all uppercase letters.
  6. Print the selected elements as a string along with a message indicating that these are the strings with the same case.

Python3

import numpy as np
 
# Creating list of strings
test_list = ["GFG", "Geeks", "best", "FOr", "all", "GEEKS"]
 
# Printing original list
print("The original list is : " + str(test_list))
 
# Convert the list into a NumPy array
arr = np.array(test_list)
 
# use NumPy's np.char.islower() and np.char.isupper() functions to create a boolean array of the same shape as arr
# that indicates whether each element of arr is lowercase or uppercase
lowercase_arr = np.char.islower(arr)
uppercase_arr = np.char.isupper(arr)
 
# use logical OR to combine the two boolean arrays element-wise
same_case_arr = lowercase_arr | uppercase_arr
 
# use the resulting boolean array to index arr, selecting only the elements that have either all lowercase or all uppercase letters
res = arr[same_case_arr]
 
# print the selected elements as a string along with a message indicating that these are the strings with the same case
print("Strings with same case : " + str(res))
# This code is contributed by Jyothi pinjala
                      
                       

Output
The original list is : ['GFG', 'Geeks', 'best', 'FOr', 'all', 'GEEKS'] Strings with same case : ['GFG', 'best', 'all', 'GEEKS']

Time Complexity: O(NM)

Creating the NumPy array using np.array() takes O(n) time, where n is the number of strings in test_list.
The np.char.islower() and np.char.isupper() functions take O(n * m) time, where m is the average length of a string in arr.
The logical OR operation using the | operator takes O(n * m) time.
Indexing the NumPy array using boolean indexing takes O(k), where k is the number of elements that have either all lowercase or all uppercase letters.
Converting the selected elements to a string using str() takes O(k * m) time.
Overall, the time complexity of the code is O(n * m).

Auxiliary Space: O(NM)

Creating the NumPy array using np.array() takes O(n * m) space.
Creating the two boolean arrays using np.char.islower() and np.char.isupper() takes O(n * m) space.
Creating the third boolean array using logical OR takes O(n * m) space.
Creating the res array using boolean indexing takes O(k * m) space.
Storing the message string takes O(1) space.
Overall, the space complexity of the code is O(n * m).

Method #5: Without any builtin methods

Steps:

  1. Initiated a for loop to traverse the list of strings
  2. Defined two methods check_lower(),check_upper() methods which will check whether the string is uppercase or lowercase by checking whether each character of the string belongs to loweralphabets or upperalphabets
  3. If the function check_lower() or check_upper() returns True then all the characters of the string belong to the same case.
  4. Append such strings to the output list.
  5. Display output list.

Python3

# Python3 code to demonstrate working of
# Filter Similar Case Strings
 
def check_lower(s):
    c = 0
    for i in s:
        if i in "abcdefghijklmnoprstuvwxyz":
            c += 1
    if(c == len(s)):
        return True
    return False
 
def check_upper(s):
    c = 0
    for i in s:
        if i in "ABCDEFGHIJKLMNOPRSTUVWXYZ":
            c += 1
    if(c == len(s)):
        return True
    return False
 
 
# Initializing Matrix
test_list = ["GFG", "Geeks",
             "best", "FOr", "all", "GEEKS"]
 
 
# Printing original list
print("The original list is : " + str(test_list))
 
res = []
for i in test_list:
    if check_upper(i) or check_lower(i):
        res.append(i)
         
# Printing result
print("Strings with same case : " + str(res))
                      
                       

Output
The original list is : ['GFG', 'Geeks', 'best', 'FOr', 'all', 'GEEKS'] Strings with same case : ['GFG', 'best', 'all', 'GEEKS']

Time Complexity: O(N), where N – length of strings list
Auxiliary Space : O(N)

Method 6: Using map() and lambda function

Steps: 

  1. Create a lambda function that takes in a string as an argument and returns True if the string contains all lowercase or all uppercase characters, otherwise False.
  2. Use the ‘map()’ function to apply the lambda function to each element in the ‘test_list’.
  3. Use the ‘filter()’ function to filter out the elements in the resulting map object that are False.
  4. Convert the resulting filter object to a list.
  5. Print the resulting list as the result.

Python3

# Python3 code to demonstrate working of
# Filter Similar Case Strings
 
# lambda function to check if string contains all lowercase
# or all uppercase characters
def check_case(s): return s.islower() or s.isupper()
 
 
# initializing Matrix
test_list = ["GFG", "Geeks", "best", "FOr", "all", "GEEKS"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using map(), filter(), and lambda function to filter out similar case strings
res = list(filter(check_case, map(str, test_list)))
 
# printing result
print("Strings with same case : " + str(res))
                      
                       

Output
The original list is : ['GFG', 'Geeks', 'best', 'FOr', 'all', 'GEEKS'] Strings with same case : ['GFG', 'best', 'all', 'GEEKS']

Time complexity: O(N), where n is the length of the ‘test_list’
Auxiliary space: O(M), where m is the number of elements that satisfy the condition, i.e., all lowercase or all uppercase characters.

Method 7: Using ASCII values

 step-by-step algorithm for the approach:

  1. Initialize an empty list res to store the result.
  2. Iterate through each string in the input list test_list.
  3. For each string, check if all characters in the string are either uppercase or lowercase.
  4. If the above condition is true, append the string to the res list.
  5. After iterating through all the strings, print the res list.

Python3

# Define the input list
test_list = ["GFG", "Geeks", "best", "FOr", "all", "GEEKS"]
 
# Initialize an empty list for the output strings with same case
res = []
 
# Iterate through each string in the input list
for string in test_list:
    # Check if all characters in the string are uppercase or lowercase
    if all(65 <= ord(c) <= 90 for c in string) or all(97 <= ord(c) <= 122 for c in string):
        # If all characters have the same case, append the string to the result list
        res.append(string)
 
# Print the result list
print("Strings with same case: " + str(res))
                      
                       

Output
Strings with same case: ['GFG', 'best', 'all', 'GEEKS']

Time Complexity: O(n*k)
Auxiliary Space :O(m)



Next Article
Similarity Metrics of Strings - Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Similarity Metrics of Strings - Python
    In Python, we often need to measure the similarity between two strings. For example, consider the strings "geeks" and "geeky" —we might want to know how closely they match, whether for tasks like comparing user inputs or finding duplicate entries. Let's explore different methods to compute string si
    3 min read
  • Python | Kth index character similar Strings
    Sometimes, we require to get the words that have the Kth index with the specific letter. This kind of use case is quiet common in places of common programming projects or competitive programming. Let’s discuss certain shorthand to deal with this problem in Python. Method #1: Using list comprehension
    3 min read
  • Python - Sort Strings by Case difference
    Given Strings List, the task is to write a Python program to perform sort on basis of difference of cases i.e count of lower case and upper case. Examples: Input : test_list = ["GFG", "GeeKs", "best", "FOr", "alL", "GEEKS"] Output : ['GeeKs', 'FOr', 'alL', 'GFG', 'best', 'GEEKS'] Explanation : ees(3
    6 min read
  • Python - Similar characters Strings comparison
    Given two Strings, separated by delim, check if both contain same characters. Input : test_str1 = 'e!e!k!s!g', test_str2 = 'g!e!e!k!s', delim = '!' Output : True Explanation : Same characters, just diff. positions. Input : test_str1 = 'e!e!k!s', test_str2 = 'g!e!e!k!s', delim = '!' Output : False Ex
    6 min read
  • Python | Grouping similar substrings in list
    Sometimes we have an application in which we require to group common prefix strings into one such that further processing can be done according to the grouping. This type of grouping is useful in the cases of Machine Learning and Web Development. Let's discuss certain ways in which this can be done.
    7 min read
  • 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() + isl
    7 min read
  • Python - Filter Strings within ASCII range
    Given ASCII or alphabetical range, filter strings are found in a particular range. Input : test_list = ["gfg", "is", "best", "for", "geeks"], strt_asc, end_asc = 105, 115 Output : ['is'] Explanation : i has 105, and s has 115, which is in range ASCII values.Input : test_list = ["gfg", "is", "best",
    3 min read
  • Python Program to check for almost similar Strings
    Given two strings, the task here is to write a python program that can test if they are almost similar. Similarity of strings is being checked on the criteria of frequency difference of each character which should be greater than a threshold here represented by K. Input : test_str1 = 'aabcdaa', test
    5 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 | 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
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