Computer >> Computer tutorials >  >> Programming >> Python

Python Program to Form a New String where the First Character and the Last Character have been Exchanged


When it is required to form a new string where the first and last characters are exchanged, a method can be defined that uses indexing to form the new string.

Below is the demonstration of the same −

Example

def exchange_val(my_string):
   return my_string[-1:] + my_string[1:-1] + my_string[:1]

my_string = “Hi there how are you”
print(“The string is :”)
print(my_string)
print(“The modified string is :”)
print(exchange_val(my_string))

Output

The string is :
Hi there how are you
The modified string is :
ui there how are yoH

Explanation

  • A method named ‘exchange_val’ is defined that takes a string as a parameter.

  • It uses indexing to exchange the first and last characters of a string.

  • Outside the method, a string is defined, and is displayed on the console.

  • This method is called by passing the string as a parameter to it.

  • This is displayed as output on the console.