Exercise 40

Write a Python algorithm to swap the first and the last word in given string text. Example if s = "Python is a programming language", the program returns the string s2 = "programming is a Python language"

Solution

# function which swap word in given text
def swap_first_and_last_words(s):
    # converting the string s to list
    words = s.split()
    if len(words) > 1:
        words[0], words[-1] = words[-1], words[0]
    return ' '.join(words)

s = "Python is a programming language"
s2 = swap_first_and_last_words(s)
print(s2) # "language is a programming Python"





In this algorithm:

  1. The input string s: is split into a list of words using the split() method.
  2. If the list of words: has more than one element (i.e., if the input string has more than one word), the first and last elements of the list are swapped using Python's multiple assignment
  3. syntax: words[0], words[-1] = words[-1], words[0].
  4. The list of words: is joined back into a string using the join() method, with a space as the separator.

 

Younes Derfoufi
CRMEF OUJDA

One thought on “Solution Exercicse 40: algorithm python to swap word in given string text”

Leave a Reply