Python Program to Reverse Words in a Sentence
Reversing words in a sentence is a common string manipulation problem in Python.
It helps build understanding of string operations, lists, and logic building.
1. Understanding the Problem
Given a sentence, reverse the order of words while keeping words intact.
Input: I love Python Output: Python love I
2. Method 1: Using split and reverse
sentence = input("Enter sentence: ")
words = sentence.split()
print(" ".join(words[::-1]))
This is the simplest and most Pythonic approach.
3. Method 2: Using Loop
sentence = input()
words = sentence.split()
reversed_words = []
for i in range(len(words)-1, -1, -1):
reversed_words.append(words[i])
print(" ".join(reversed_words))
Manually builds reversed list.
4. Method 3: Using Stack
sentence = input()
stack = sentence.split()
result = []
while stack:
result.append(stack.pop())
print(" ".join(result))
Uses LIFO principle of stack.
5. Method 4: Using Function
def reverse_words(s):
return " ".join(s.split()[::-1])
print(reverse_words("Hello World Python"))
Encapsulates logic for reuse.
6. Method 5: Handling Edge Cases
sentence = input().strip()
if not sentence:
print("Empty input")
else:
print(" ".join(sentence.split()[::-1]))
Handles empty or whitespace-only input.
7. Algorithm
1. Split sentence into words.
2. Reverse word list.
3. Join words back into sentence.
4. Print result.
8. Common Mistakes
1. Reversing characters instead of words.
2. Not handling extra spaces.
3. Forgetting split/join usage.
4. Empty input not handled.
9. Applications
1. Text processing.
2. Chat applications.
3. NLP preprocessing.
4. Interview coding tests.
Conclusion
Reversing words in a sentence is a simple but powerful string manipulation problem.
Python makes it very easy using split and slicing techniques.
Codecrown