Python program to Sort Strings by Punctuation count


When it is required to sort strings by punctuation count, a method is defined that takes a string as a parameter and uses list comprehension and ‘in’ operator to determine the result.

Below is a demonstration of the same −

Example

 Live Demo

from string import punctuation

def get_punctuation_count(my_str):
   return len([element for element in my_str if element in punctuation])

my_list = ["python@%^", "is", "fun!", "to@#r", "@#$learn!"]

print("The list is :")
print(my_list)

my_list.sort(key = get_punctuation_count)

print("The result is :")
print(my_list)

Output

The list is :
['python@%^', 'is', 'fun!', 'to@#r', '@#$learn!']
The result is :
['is', 'fun!', 'to@#r', 'python@%^', '@#$learn!']

Explanation

  • The required packages are imported into the environment.

  • A method named ‘get_punctuation_count’ is defined that takes string as a parameter, and iterates over the elements using list comprehension.

  • It checks to see if a string contains a punctuation.

  • It returns the length of the string containing punctuation symbol as output.

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

  • The list is sorted using ‘sort’ method and the key is specified as the previously defined method.

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

Updated on: 06-Sep-2021

186 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements