Exercise 20

Write a simple program in Python that exchanges the first and last characters of a given string


def exchange_first_last(string):
    if len(string) < 2:
        return string
        return string[-1] + string[1:-1] + string[0]

string = input("Enter a string: ")
new_string = exchange_first_last(string)
print("Original string:", string)
print("New string:", new_string)
Enter a string: hello
Original string: hello
New string: oellh

In this program:

  1. the exchange_first_last() function: takes a string as input and returns a new string where the first and last characters have been exchanged.
  2. If the input string has length less than 2: the function simply returns the original string unchanged.
  3. The input() function: is used to prompt the user to enter a string, which is then passed to the exchange_first_last function. The resulting new string is then printed out to the console.


Younes Derfoufi

One thought on “Solution Exercise 20: python algorithm to swap letters in given word”

Leave a Reply