Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Sort Words Alphabetically

Sort whitespace-separated words using Python's default string ordering. Students compare a sorted copy with the token order and recognize case-sensitive results.

IntermediatePhase 5 - Category 3: Word OperationsExample 10 of 10
sort-words-alphabetically.py
1# Take string input
2s = input("Enter a string: ")
3
4# Sort words
5words = s.split()
6sorted_words = sorted(words)
7result = " ".join(sorted_words)
8
9print(f"Sorted: {result}")

Output

Enter a string: world hello programming
Sorted: hello programming world

In this one

  • Use default string ordering
  • Retain repeated words
  • Create a sorted copy

How it works

  1. 1

    Split s into tokens.

  2. 2

    Create sorted_words with sorted.

  3. 3

    Join that list with spaces and print.

Edge cases

Are duplicates removed?

Are duplicates removed?

No. Sorting preserves every token.

Does sorting ignore case?

Does sorting ignore case?

No. No lowercase key is supplied.

What's going on

sorted(words) creates a new ordered list after split. The default comparison follows Unicode string order rather than a locale-aware dictionary.

Uppercase and lowercase tokens can therefore group differently from a human alphabetic expectation. Punctuation also participates. join builds the displayed text with single spaces and does not modify the original string or normalize letter case.

Are duplicates removed? No. Sorting preserves every token.

Does sorting ignore case? No. No lowercase key is supplied.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does sorted return?

Pick an answer to check it.

Question 2

Are duplicates removed?

Pick an answer to check it.

Questions people ask

Are duplicates removed?

No. Sorting preserves every token.

Does sorting ignore case?

No. No lowercase key is supplied.

What does sorted return?

A new list.