Exercise 40

Write a Python algorithm which swap the first with the last word in a given string 's'. Example: if s = "Python is a programming language", the program returns the string s2 = "language is a programming Python"


def swap_first_last(s):
    # Split string into words
    words = s.split()

    # Check that there are at least two words in the list
    if len(words) < 2:
        return s

    # Swap first and last words
    words[0], words[-1] = words[-1], words[0]

    # Join words back into a string and return the result
    return ' '.join(words)

# Example usage
s = "Python is a programming language"
s2 = swap_first_last(s)
# output: "language is a programming Python"


Younes Derfoufi

Leave a Reply