Python Practice › String Programs › Program 12

Swap first and last letters of each word

EasyString Programs · 12 of 106

Write a Python program to exchange the first and last characters of every word in a string.

Advertisement
Input
"Its Online Learning"
Output
stI enlinO gearninL

Approach

  1. Split, swap each word, join again.

Solution

Python
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.

More string programs

← All 106 String Programs

Leave a Comment