Swap First and Last Character
Swap a string's endpoint characters with concatenation and slicing. Students retain the middle substring and require at least two positions before swapping.
1# Take string input2s = input("Enter a string: ")34# Swap first and last5if len(s) >= 2:6 result = s[-1] + s[1:-1] + s[0]7 print(f"After swap: {result}")8else:9 print("String too short")
Output
Enter a string: Hello After swap: oellH
In this one
- Swap immutable-text endpoints
- Retain the middle slice
- Require two positions
How it works
- 1
Require len(s) at least two.
- 2
Concatenate last character, middle slice, and first character.
- 3
Print result or the too-short message.
Edge cases
What happens for two characters?
What happens for two characters?
They exchange positions with an empty middle slice.
What happens for one character?
What happens for one character?
String too short is printed.
What's going on
The result begins with s[-1], continues with s[1:-1], and ends with s[0]. This assembles a new string rather than editing immutable text.
For abcd, the result is dbca. With exactly two characters, the middle slice is empty and the pair reverses. Inputs shorter than two take the message branch, avoiding indexing and duplicating a sole character.
What happens for two characters? They exchange positions with an empty middle slice.
What happens for one character? String too short is printed.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which part keeps the middle unchanged?
Pick an answer to check it.
Question 2
What happens for two characters?
Pick an answer to check it.
Questions people ask
What happens for two characters?
They exchange positions with an empty middle slice.
What happens for one character?
String too short is printed.
Which part keeps the middle unchanged?
s[1:-1].
๐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