How to Sort Text Alphabetically in Python

Sort words or lines alphabetically with case-insensitive ordering while preserving original casing.

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

Python code

32 lines
Python 3.9+
def sort_words(text):
    """Sort words alphabetically (case-insensitive), preserving case."""
    words = text.split()
    return sorted(words, key=str.lower)


def sort_lines(text):
    """Sort lines alphabetically (case-insensitive), preserving case."""
    lines = [line for line in text.splitlines() if line.strip()]
    return sorted(lines, key=str.lower)


def process_text(text, mode="words"):
    """Main processor: sorts text by words or lines."""
    if mode == "words":
        result = sort_words(text)
        return " ".join(result)
    elif mode == "lines":
        result = sort_lines(text)
        return "\n".join(result)
    else:
        raise ValueError("Mode must be 'words' or 'lines'")


if __name__ == "__main__":
    sample_text = "banana apple Cherry date"
    print("Original:", sample_text)
    print("Sorted words:", process_text(sample_text, "words"))

    multi_line = "banana\napple\nCherry\ndate"
    print("\nOriginal lines:\n" + multi_line)
    print("\nSorted lines:\n" + process_text(multi_line, "lines"))

Output

stdout
Original: banana apple Cherry date
Sorted words: apple banana Cherry date

Original lines:
banana
apple
Cherry
date

Sorted lines:
apple
banana
Cherry
date

How it works

The sorted() function returns a new list in ascending order. Passing key=str.lower makes sorting case-insensitive while keeping the original letter casing in the output. text.split() splits on whitespace for words, while splitlines() handles newline characters for lines. The list comprehension filters out blank lines so empty strings don't appear in the output. Each mode produces a string joined with the appropriate separator — spaces for words, newlines for lines.

Common mistakes

  • Sorting with default case-sensitive order, which places uppercase before lowercase
  • Using `split()` for lines instead of `splitlines()` when handling multi-line text
  • Forgetting to filter empty lines, which causes trailing newlines in output

Variations

  1. Use `sorted(text.split(), key=lambda w: w.lower())` for the same result
  2. Add `reverse=True` to sort in descending order

Real-world use cases

  • Sorting a list of usernames or product names for display in a UI where case should not affect ordering.
  • Organizing configuration keys or environment variable names alphabetically before printing them for debugging.
  • Preparing alphabetical indexes or glossaries from raw text files in documentation tooling.

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.