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.

Easy Python 3.9+ Aug 9, 2026 Strings & text 12 views 0 copies

Python code

18 lines
Python 3.9+
def 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

stdout
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

  1. Use `casefold()` to sort case-insensitively: `sorted(words, key=str.casefold)`
  2. Sort by string length instead: `sorted(words, key=len)`
  3. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.