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

Reverse Words in String

Reorder whole words without reversing their letters. Students contrast blue red with der eulb and trace whitespace normalization in split, reverse, and join.

AdvancedPhase 5 - Category 5: Advanced String LogicExample 14 of 14
reverse-words-in-string.py
1# Take string
2s = input("Enter string: ")
3
4# Reverse words
5words = s.split()
6reversed_words = words[::-1]
7result = ' '.join(reversed_words)
8
9print(f"Reversed: {result}")

Output

Enter string: Hello World Programming
Reversed: Programming World Hello

In this one

  • Distinguish words from characters
  • Keep token spelling intact
  • Normalize output whitespace

How it works

  1. 1

    Create whole-word tokens using split.

  2. 2

    Reverse only the token list.

  3. 3

    Join them with single spaces and print Reversed.

Edge cases

What is red blue changed to?

What is red blue changed to?

blue red.

Are letters inside red reversed?

Are letters inside red reversed?

No. A word remains an intact list element.

What's going on

Reversing words is not reversing characters: red blue must become blue red, not eulb der. The code therefore reverses a list of complete tokens.

split produces those tokens, slicing changes their positions, and a single-space join rebuilds the sentence. Each token's spelling stays untouched, including attached punctuation. This lesson emphasizes choosing the correct unit of reversal; original spacing cannot survive the split-and-join pipeline.

What is red blue changed to? blue red.

Are letters inside red reversed? No. A word remains an intact list element.

Quiz

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

Question 1

What is lost during split and join?

Pick an answer to check it.

Question 2

What is red blue changed to?

Pick an answer to check it.

Questions people ask

What is red blue changed to?

blue red.

Are letters inside red reversed?

No. A word remains an intact list element.

What is lost during split and join?

Original whitespace layout.