

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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
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.
- Related Questions & Answers
- Python program to sort strings by substring range
- Python – Sort Strings by Case difference
- Python – Sort Matrix by Palindrome count
- Python Program to sort rows of a matrix by custom element count
- Python program to Sort a List of Strings by the Number of Unique Characters
- Python – Sort by Rear Character in Strings List
- Python – Sort a List by Factor count
- Program to count sorted vowel strings in Python
- Python program to count the pairs of reverse strings
- Python program to Sort Tuples by their Maximum element
- Python – Sort by a particular digit count in elements
- Program to count the number of consistent strings in Python
- Python – Sort given list of strings by numeric part of string
- Python Program to Group Strings by K length Using Suffix
- Python program to sort a tuple by its float element