How to Sort Text Alphabetically in Python
Sort words or lines alphabetically with case-insensitive ordering while preserving original casing.
Python code
32 linesdef 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
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
- Use `sorted(text.split(), key=lambda w: w.lower())` for the same result
- 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
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.