Swap First and Last Word
Swap first and last word in string.
IntermediatePhase 5 - Category 3: Word OperationsExample 7 of 10
swap-first-and-last-word.py
1# Take string input2s = input("Enter a string: ")34# Swap first and last word5words = s.split()6if len(words) >= 2:7 words[0], words[-1] = words[-1], words[0]8 result = " ".join(words)9 print(f"After swap: {result}")10else:11 print("Need at least 2 words")
Output
Enter a string: Hello World Programming After swap: Programming World Hello
What's going on
Swap first and last elements of word list.
Key Concepts:
Split into words
Swap words[0] and words[-1]
Join back
🔗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