Exercise 40 

Write a Python program that allows you to swap the first and the last word. Example if s = "Python is a programming language", the program returns the string s2 = "programming is a Python language"

Solution:

def swapWord(s):
# converting the string s to a python list
L = s.split()
n = len(L)
# getting the first and the last word
first = L[0]
last = L[n-1]
# create a substring s1 by deleting the the first and last word
s1 = " "
for i in range(1,n-1):
s1 = s1 + L[i] + " "
# swapping the first and the last word
s2 = last + s1 + first
return s2
s = "Python is a programming language"
print("The string obteined by swaping the the first and the last word is :n", swapWord(s))
Younes Derfoufi
my-courses.net

Leave a Reply