Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python – Filter Similar Case Strings
When it is required to filter similar case strings, list comprehension can be used along with isupper() and islower() methods. This technique helps identify strings that are either completely uppercase or completely lowercase, filtering out mixed-case strings.
Example
Below is a demonstration of filtering strings with consistent casing ?
my_list = ["Python", "good", "FOr", "few", "CODERS"]
print("The list is :")
print(my_list)
my_result = [sub for sub in my_list if sub.islower() or sub.isupper()]
print("The strings with same case are :")
print(my_result)
Output
The list is : ['Python', 'good', 'FOr', 'few', 'CODERS'] The strings with same case are : ['good', 'few', 'CODERS']
How It Works
The list comprehension iterates through each string and applies two conditions:
-
sub.islower()− ReturnsTrueif all alphabetic characters are lowercase -
sub.isupper()− ReturnsTrueif all alphabetic characters are uppercase - The
oroperator includes strings that satisfy either condition
Alternative Approach Using Filter
You can also use the filter() function for the same result ?
my_list = ["Python", "good", "FOr", "few", "CODERS"]
my_result = list(filter(lambda x: x.islower() or x.isupper(), my_list))
print("The strings with same case are :")
print(my_result)
The strings with same case are : ['good', 'few', 'CODERS']
Key Points
- Mixed-case strings like "Python" and "FOr" are filtered out
-
islower()andisupper()only check alphabetic characters - Strings with numbers or symbols follow special rules for case checking
Conclusion
Use list comprehension with islower() or isupper() to filter strings with consistent casing. This approach effectively separates mixed-case strings from those with uniform letter casing.
Advertisements
