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

Reverse Each Word

Reverse the letters inside each word while keeping word order. Students combine split, a list comprehension, character slicing, and a final single-space join.

IntermediatePhase 5 - Category 4: String TransformationExample 10 of 10
reverse-each-word.py
1# Take string input
2s = input("Enter a string: ")
3
4# Reverse each word
5words = s.split()
6reversed_words = [word[::-1] for word in words]
7result = " ".join(reversed_words)
8
9print(f"Result: {result}")

Output

Enter a string: Hello World
Result: olleH dlroW

In this one

  • Reverse each token's characters
  • Retain token order
  • Normalize whitespace

How it works

  1. 1

    Split the source into words.

  2. 2

    Build reversed_words from word[::-1] for each token.

  3. 3

    Join that list without reversing its order.

Edge cases

Is original word order changed?

Is original word order changed?

No. Each word stays in its list position.

Are repeated spaces retained?

Are repeated spaces retained?

No. split and join normalize them.

What's going on

The comprehension applies word[::-1] to each token separately. It never reverses the word list itself.

For red blue, the result is der eulb rather than blue red. split without arguments normalizes whitespace, and punctuation moves with the character reversal inside its token. join restores one space between the reversed tokens, leaving the original string unchanged.

Is original word order changed? No. Each word stays in its list position.

Are repeated spaces retained? No. split and join normalize them.

Quiz

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

Question 1

What is reversed by [::-1]?

Pick an answer to check it.

Question 2

Is original word order changed?

Pick an answer to check it.

Questions people ask

Is original word order changed?

No. Each word stays in its list position.

Are repeated spaces retained?

No. split and join normalize them.

What is reversed by [::-1]?

Each individual word.