How to Sort Text in Python with a Simple Helper Function
A compact helper function that sorts a list of strings or splits a string into words and sorts them alphabetically, with optional reverse ordering.
Python code
18 linesdef sort_text(data, reverse=False):
"""
Sort a list of strings (or a single string split into words) alphabetically.
"""
if isinstance(data, str):
words = data.split()
else:
words = [str(item) for item in data]
return sorted(words, reverse=reverse)
if __name__ == "__main__":
sample_text = "banana apple cherry date"
print("Ascending:", sort_text(sample_text))
print("Descending:", sort_text(sample_text, reverse=True))
mixed_list = ["pear", "grape", "kiwi", "mango"]
print("List sorted:", sort_text(mixed_list))
Output
Ascending: ['apple', 'banana', 'cherry', 'date']
Descending: ['date', 'cherry', 'banana', 'apple']
List sorted: ['grape', 'kiwi', 'mango', 'pear']
How it works
The function uses isinstance() to detect whether the input is a single string or a list. If it's a string, split() breaks it into words at whitespace; otherwise, items are converted to strings with str() to avoid type errors. The built-in sorted() returns a new sorted list without modifying the original, with reverse=True flipping the order. This approach is clean, readable, and uses only the standard library.
Common mistakes
- Assuming `sorted()` modifies the original list in place — it returns a new list instead
- Forgetting to handle non-string list items, causing a TypeError during comparison
- Calling `.sort()` on a string, which fails because strings are immutable
Variations
- Use `casefold()` to sort case-insensitively: `sorted(words, key=str.casefold)`
- Sort by string length instead: `sorted(words, key=len)`
- Pass `reverse=True` to `sort_text` when you need descending alphabetical order
Real-world use cases
- Preparing a list of product names for an alphabetized dropdown menu in a web app.
- Sorting log file lines by first word before grouping them in a diagnostic report.
- Ordering tags or keywords alphabetically before saving them to a database field.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.