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.
1# Take string2s = input("Enter string: ")34# Reverse words5words = s.split()6reversed_words = words[::-1]7result = ' '.join(reversed_words)89print(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
Create whole-word tokens using split.
- 2
Reverse only the token list.
- 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.
๐Related Content
- ๐
Phase 5 - Learn Concepts
Review Phase 5 concepts and explanations
- ๐
Phase 5 - Quiz
Test your Phase 5 understanding with quiz questions
- ๐ป
Phase 5 - All Practice Problems
Explore all practice problems for Phase 5
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum