Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Extract Sorted Strings
When you need to filter strings that have their characters in sorted order, you can use list comprehension with the sorted() method. A sorted string is one where the characters appear in alphabetical order.
Example
Below is a demonstration of extracting sorted strings from a list ?
my_list = ["pyt", "Fdf", "Fun"]
print("The list is :")
print(my_list)
my_result = [element for element in my_list if ''.join(sorted(element)) == element]
print("The result is :")
print(my_result)
Output
The list is : ['pyt', 'Fdf', 'Fun'] The result is : ['Fdf']
How It Works
The algorithm checks each string by:
Sorting characters:
sorted(element)returns a list of characters in alphabetical orderJoining back:
''.join(sorted(element))creates a string with sorted charactersComparing: If the sorted version equals the original, the string is already sorted
Multiple Examples
words = ["abc", "zyx", "def", "hello", "ayz"]
sorted_words = [word for word in words if ''.join(sorted(word)) == word]
print("Original words:", words)
print("Sorted words:", sorted_words)
Original words: ['abc', 'zyx', 'def', 'hello', 'ayz'] Sorted words: ['abc', 'def']
Case-Sensitive vs Case-Insensitive
words = ["Abc", "def", "XYZ"]
# Case-sensitive (uppercase letters come first)
case_sensitive = [word for word in words if ''.join(sorted(word)) == word]
# Case-insensitive
case_insensitive = [word for word in words if ''.join(sorted(word.lower())) == word.lower()]
print("Case-sensitive result:", case_sensitive)
print("Case-insensitive result:", case_insensitive)
Case-sensitive result: ['XYZ'] Case-insensitive result: ['Abc', 'def']
Conclusion
Use list comprehension with sorted() to extract strings with alphabetically ordered characters. Remember that sorting is case-sensitive by default, with uppercase letters coming before lowercase letters.
