
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort Strings by Punctuation Count in Python
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
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.