Python Practice › String Programs › Program 11
Swap the first and last characters
Write a Python program to swap the first and last characters of a string.
Input
"SqaTool"
Output
lqaTooS
Approach
- Build last + middle + first.
Solution
text = "SqaTool"swapped = text[-1] + text[1:-1] + text[0] if len(text) > 1 else textprint(swapped)Output
lqaTooS
Line by line
Line 2
text[1:-1] is everything between the first and last characters.
Note
The original sample showed “IqaTooS” with a capital I, but swapping keeps the original letters, so the result is “lqaTooS”.
Learn the concept
New to this topic? Read the lesson, then come back.