Python Practice › String Programs › Program 12
Swap first and last letters of each word
Write a Python program to exchange the first and last characters of every word in a string.
Input
"Its Online Learning"
Output
stI enlinO gearninL
Approach
- Split, swap each word, join again.
Solution
def swap(word): return word if len(word) < 2 else word[-1] + word[1:-1] + word[0] text = "Its Online Learning"print(" ".join(swap(w) for w in text.split()))Output
stI enlinO gearninL
Line by line
Line 2
One-letter words are returned unchanged.
Learn the concept
New to this topic? Read the lesson, then come back.