Python program to Sort Strings by Punctuation count
Last Updated :
26 Apr, 2023
Given the Strings list, sort by punctuations count.
Input : test_list = ["gfg@%^", "is", "Best!"]
Output : ['is', 'Best!', 'gfg@%^']
Explanation : 0 < 1 < 3, sorted by punctuation count.
Input : test_list = ["gfg@%^", "Best!"]
Output : [ 'Best!', 'gfg@%^']
Explanation : 1 < 3, sorted by punctuation count.
Method #1 : Using string.punctuation + sort()
In this, sorting is done using sort() and punctuations are extracted from punctuation pool from string library. Performs inplace sort.
Python3
# Python3 code to demonstrate working of
# Sort Strings by Punctuation count
# Using string.punctuation + sort()
from string import punctuation
def get_pnc_count(string):
# getting punctuation count
return len([ele for ele in string if ele in punctuation])
# initializing list
test_list = ["gfg@%^", "is", "Best!", "fo@#r", "@#$ge24eks!"]
# printing original list
print("The original list is : " + str(test_list))
# performing inplace sort
test_list.sort(key = get_pnc_count)
# printing result
print("Sorted Strings list : " + str(test_list))
Output:
The original list is : ['gfg@%^', 'is', 'Best!', 'fo@#r', '@#$ge24eks!']
Sorted Strings list : ['is', 'Best!', 'fo@#r', 'gfg@%^', '@#$ge24eks!']
Time Complexity: O(n*nlogn)
Auxiliary Space: O(1)
Method #2 : Using sorted() + punctuation + lambda
In this, we perform sort using sorted() using lambda to avoid external function to perform task of filtering punctuations extracted using punctuation.
Python3
# Python3 code to demonstrate working of
# Sort Strings by Punctuation count
# Using sorted() + punctuation + lambda
from string import punctuation
# initializing list
test_list = ["gfg@%^", "is", "Best!", "fo@#r", "@#$ge24eks!"]
# printing original list
print("The original list is : " + str(test_list))
# performing sort using sorted() with lambda
# function for filtering
res = sorted(test_list, key=lambda string: len(
[ele for ele in string if ele in punctuation]))
# printing result
print("Sorted Strings list : " + str(res))
Output:
The original list is : ['gfg@%^', 'is', 'Best!', 'fo@#r', '@#$ge24eks!']
Sorted Strings list : ['is', 'Best!', 'fo@#r', 'gfg@%^', '@#$ge24eks!']
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3: Using re
This approach uses a regular expression pattern r'[^\w\s]' to match any character that is not a word character (letters, digits, and underscores) or whitespace. The re.findall() function returns a list of all non-overlapping matches as strings.
Python3
import re
def get_punctuation_count(string):
return len(re.findall(r'[^\w\s]', string))
test_list = ["gfg@%^", "is", "Best!", "fo@#r", "@#$ge24eks!"]
print("The original list is: ", test_list)
res = sorted(test_list, key=get_punctuation_count)
print("Sorted Strings list: ", res)
OutputThe original list is: ['gfg@%^', 'is', 'Best!', 'fo@#r', '@#$ge24eks!']
Sorted Strings list: ['is', 'Best!', 'fo@#r', 'gfg@%^', '@#$ge24eks!']
Time complexity: O(n)
Auxiliary space: O(n)
Method 4: Use the Counter module from collections.
Step-by-step approach:
- Import the Counter module from collections.
- Define a function that takes a string and returns the count of its punctuation characters using Counter.
- Initialize the list of strings to be sorted.
- Use sorted() function with a lambda function that calls the function defined in step 2 for each string in the list.
- Print the sorted list.
Python3
from string import punctuation
from collections import Counter
# Function to count punctuation characters in a string
def count_punct(string):
return sum(Counter(string)[c] for c in punctuation)
# initializing list
test_list = ["gfg@%^", "is", "Best!", "fo@#r", "@#$ge24eks!"]
# printing original list
print("The original list is : " + str(test_list))
# performing sort using sorted() with lambda
# function for filtering
res = sorted(test_list, key=lambda string: count_punct(string))
# printing result
print("Sorted Strings list : " + str(res))
OutputThe original list is : ['gfg@%^', 'is', 'Best!', 'fo@#r', '@#$ge24eks!']
Sorted Strings list : ['is', 'Best!', 'fo@#r', 'gfg@%^', '@#$ge24eks!']
Time complexity: O(n)
Auxiliary space: O(n)
Similar Reads
Python Program to Sort a String
Sorting strings in Python is a common and important task, whether we need to organize letters alphabetically or systematically handle text data. In this article, we will explore different methods to sort a string starting from the most efficient to the least.Using sorted with join()sorted() function
2 min read
Python - Split String on all punctuations
Given a String, Split the String on all the punctuations. Input : test_str = 'geeksforgeeks! is-best' Output : ['geeksforgeeks', '!', 'is', '-', 'best'] Explanation : Splits on '!' and '-'. Input : test_str = 'geek-sfo, rgeeks! is-best' Output : ['geek', '-', 'sfo', ', ', 'rgeeks', '!', 'is', '-', '
3 min read
Python - Remove Punctuation from String
In this article, we will explore various methods to Remove Punctuations from a string.Using str.translate() with str.maketrans()str.translate() method combined with is str.maketrans() one of the fastest ways to remove punctuation from a string because it works directly with string translation tables
2 min read
Python program to list Sort by Number value in String
Given a List of strings, the task is to write a Python program to sort list by the number present in the Strings. If no number is present, they will be taken to the front of the list. Input : test_list = ["gfg is 4", "all no 1", "geeks over 7 seas", "and 100 planets"] Output : ['all no 1', 'gfg is 4
6 min read
Python program to sort strings by substring range
Given a String List, sort by a range of substrings. Input : test_list = ["geeksforgeeks", "best", "geeks", "preparation", "interview"], i, j = 1, 3 Output : ['geeksforgeeks', 'geeks', 'best', 'interview', 'preparation'] Explanation : "eek" < "eek" < "est" < "nte" < "rep". Input : test_li
5 min read
Python - Strip front and rear Punctuations from given String
Given a string strip rear and front punctuations. Input : test_str = '%$Gfg is b!!est(*^' Output : Gfg is b!!est Explanation : Front and rear punctuations are stripped. Input : test_str = '%Gfg is b!!est(*^' Output : Gfg is b!!est Explanation : Front and rear punctuations are stripped. Method #1 : U
6 min read
Python - Substring concatenation by Separator
Sometimes, while working with Python Lists, we can have problem in which we need to perform the concatenation of strings in a list till the separator. This can have application in domains in which we need chunked data. Lets discuss certain ways in which this task can be performed. Method #1 : Using
5 min read
Python - Reverse String except punctuations
Given a string with punctuations, perform string reverse, leaving punctuations at their places. Input : test_str = 'geeks@#for&%%gee)ks' Output : skeeg@#rof&%%ske)eg Explanation : Whole string is reversed, except the punctuations. Input : test_str = 'geeks@#for&%%gee)ks' [ only substring
5 min read
Python - Sort String by Custom Integer Substrings
Given a list of strings, sort strings by the occurrence of substring from list. Input : test_list = ["Good at 4", "Wake at 7", "Work till 6", "Sleep at 11"], subord_list = ["11", "7", "4", "6"] Output : ['Sleep at 11', 'Wake at 7', 'Good at 4', 'Work till 6'] Explanation : Strings sorted by substrin
5 min read
How to sort a list of strings in Python
In this article, we will explore various methods to sort a list of strings in Python. The simplest approach is by using sort().Using sort() MethodThe sort() method sorts a list in place and modifying the original list directly.Pythona = ["banana", "apple", "cherry"] # Sorting list in place a.sort()
2 min read