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
Python – Sort Strings by Case difference
When working with strings in Python, you may need to sort them based on the case difference ? the absolute difference between uppercase and lowercase letters. This technique uses custom sorting with the sort() method and a key function that calculates case differences.
Understanding Case Difference
Case difference is calculated by counting uppercase and lowercase letters in each string, then finding their absolute difference. Strings with smaller case differences are considered "more balanced" and appear first when sorted.
Example
Here's how to sort strings by case difference using a custom function ?
def get_diff(my_string):
lower_count = len([ele for ele in my_string if ele.islower()])
upper_count = len([ele for ele in my_string if ele.isupper()])
return abs(lower_count - upper_count)
my_list = ["Abc", "Python", "best", "hello", "coders"]
print("The list is :")
print(my_list)
my_list.sort(key=get_diff)
print("Sorted Strings by case difference :")
print(my_list)
The output of the above code is ?
The list is : ['Abc', 'Python', 'best', 'hello', 'coders'] Sorted Strings by case difference : ['Abc', 'Python', 'best', 'coders', 'hello']
How It Works
The get_diff() function calculates case difference for each string:
"Abc" has 1 uppercase, 2 lowercase ? difference = |1-2| = 1
"Python" has 1 uppercase, 5 lowercase ? difference = |1-5| = 4
"best" has 0 uppercase, 4 lowercase ? difference = |0-4| = 4
"hello" has 0 uppercase, 5 lowercase ? difference = |0-5| = 5
"coders" has 0 uppercase, 6 lowercase ? difference = |0-6| = 6
Using Lambda Function
You can make this more concise using a lambda function ?
strings = ["ABC", "hello", "PyThOn", "world"]
strings.sort(key=lambda s: abs(sum(1 for c in s if c.isupper()) - sum(1 for c in s if c.islower())))
print("Sorted by case difference:")
print(strings)
Sorted by case difference: ['PyThOn', 'ABC', 'hello', 'world']
Conclusion
Sorting strings by case difference uses sort() with a custom key function that calculates the absolute difference between uppercase and lowercase letter counts. This technique helps organize strings by their case balance.
