Python – Sort Strings by Case difference


When it is required to sort strings based on case difference, a method is defined that takes a string as a parameter. This method uses list comprehension and ‘isupper’ and ‘islower’ methods along with list comprehension to get case difference. Their difference gives the sorted values.

Example

Below is a demonstration of the same

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)

Output

The list is :
['Abc', 'Python', 'best', ‘hello’, 'coders']
Sorted Strings by case difference :
['Abc', 'Python', 'best', 'coders', ‘hello’]

Explanation

  • A method named ‘get_diff’ is defined that takes a list of strings as a parameter.

  • List comprehension and ‘islower’ and ‘isupper’ methods are used to check if the strings are upper or lower case.

  • These values are stored in two different variables.

  • The absolute difference between these two variables is returned as output.

  • Outside the method, a list is defined and is displayed on the console.

  • The list is sorted based on the previously defined method.

  • This is the output that is displayed on the console.

Updated on: 16-Sep-2021

85 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements