Python – Filter Similar Case Strings
Last Updated : 18 May, 2023
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
test_list = [ "GFG" , "Geeks" ,
"best" , "FOr" , "all" , "GEEKS" ]
print ( "The original list is : " + str (test_list))
res = [sub for sub in test_list if sub.islower() or sub.isupper()]
print ( "Strings with same case : " + str (res))
|
OutputThe 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
test_list = [ "GFG" , "Geeks" , "best" ,
"FOr" , "all" , "GEEKS" ]
print ( "The original list is : " + str (test_list))
res = list ( filter ( lambda sub : sub.islower() or sub.isupper(), test_list))
print ( "Strings with same case : " + str (res))
|
OutputThe 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)
- Import the ‘re’ library.
- Create a list of strings named ‘test_list’ and print the original list ‘test_list’.
- Use a list comprehension to iterate through ‘test_list’ and filter out the strings which have all uppercase or all lowercase letters.
- Use re.match function to match the pattern of uppercase or lowercase in each string.
- The pattern ‘[A-Z]+’ matches one or more uppercase letters and the pattern ‘[a-z]+’ matches one or more lowercase letters.
- The ‘^’ sign indicates the start of the string, and the ‘$’ sign indicates the end of the string.
- Append the matched strings to the list ‘res’.
- 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))
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))
|
OutputThe 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:
- Create a list of strings called test_list.
- Convert the list into a NumPy array called arr.
- 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.
- 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.
- Use the resulting boolean array to index arr, selecting only the elements that have either all lowercase or all uppercase letters.
- 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
test_list = [ "GFG" , "Geeks" , "best" , "FOr" , "all" , "GEEKS" ]
print ( "The original list is : " + str (test_list))
arr = np.array(test_list)
lowercase_arr = np.char.islower(arr)
uppercase_arr = np.char.isupper(arr)
same_case_arr = lowercase_arr | uppercase_arr
res = arr[same_case_arr]
print ( "Strings with same case : " + str (res))
|
OutputThe 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:
- Initiated a for loop to traverse the list of strings
- 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
- If the function check_lower() or check_upper() returns True then all the characters of the string belong to the same case.
- Append such strings to the output list.
- Display output list.
Python3
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
test_list = [ "GFG" , "Geeks" ,
"best" , "FOr" , "all" , "GEEKS" ]
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)
print ( "Strings with same case : " + str (res))
|
OutputThe 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:
- 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.
- Use the ‘map()’ function to apply the lambda function to each element in the ‘test_list’.
- Use the ‘filter()’ function to filter out the elements in the resulting map object that are False.
- Convert the resulting filter object to a list.
- Print the resulting list as the result.
Python3
def check_case(s): return s.islower() or s.isupper()
test_list = [ "GFG" , "Geeks" , "best" , "FOr" , "all" , "GEEKS" ]
print ( "The original list is : " + str (test_list))
res = list ( filter (check_case, map ( str , test_list)))
print ( "Strings with same case : " + str (res))
|
OutputThe 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:
- Initialize an empty list res to store the result.
- Iterate through each string in the input list test_list.
- For each string, check if all characters in the string are either uppercase or lowercase.
- If the above condition is true, append the string to the res list.
- After iterating through all the strings, print the res list.
Python3
test_list = [ "GFG" , "Geeks" , "best" , "FOr" , "all" , "GEEKS" ]
res = []
for string in test_list:
if all ( 65 < = ord (c) < = 90 for c in string) or all ( 97 < = ord (c) < = 122 for c in string):
res.append(string)
print ( "Strings with same case: " + str (res))
|
OutputStrings with same case: ['GFG', 'best', 'all', 'GEEKS']
Time Complexity: O(n*k)
Auxiliary Space :O(m)
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