Python program to Sort Strings by Punctuation count

When you need to sort strings by their punctuation count, you can define a custom function that counts punctuation marks and use it as a sorting key. This technique uses Python's string.punctuation module and list comprehension to efficiently count punctuation characters.

Example

Here's how to sort strings based on the number of punctuation marks they contain ?

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)
The list is :
['python@%^', 'is', 'fun!', 'to@#r', '@#$learn!']
The result is :
['is', 'fun!', 'to@#r', 'python@%^', '@#$learn!']

How It Works

The get_punctuation_count() function uses list comprehension to iterate through each character in the string and checks if it exists in Python's punctuation constant. The punctuation string contains all ASCII punctuation characters like !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~.

When sort() is called with key=get_punctuation_count, it applies this function to each string and sorts based on the returned count. Strings with fewer punctuation marks appear first in the sorted result.

Alternative Using Lambda

You can achieve the same result using a lambda function for more concise code ?

from string import punctuation

words = ["hello!", "world@#", "python", "code$%^"]

sorted_words = sorted(words, key=lambda s: sum(1 for c in s if c in punctuation))

print("Original:", words)
print("Sorted:", sorted_words)
Original: ['hello!', 'world@#', 'python', 'code$%^']
Sorted: ['python', 'hello!', 'world@#', 'code$%^']

Conclusion

Sorting strings by punctuation count is accomplished by defining a function that counts punctuation characters and using it as a key parameter in Python's sort() method. This approach efficiently organizes strings from least to most punctuation marks.

Updated on: 2026-03-26T01:06:01+05:30

328 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements