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”
# 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, words[-1] = words[-1], words 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:
- The input string s: is split into a list of words using the split() method.
- 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
- syntax: words, words[-1] = words[-1], words.
- The list of words: is joined back into a string using the join() method, with a space as the separator.