Write a Python program to change a given string to a new string where the first and last chars have been exchanged


This program is written in the Python programming language and it swaps the first and last characters of a given string. It does this in three steps:

  • The first step is to assign the first and last characters of the string "Python" to two variables named "s" and "e", respectively.
  • In the second step, the program creates a new string "res" by concatenating the following:
    • The last character stored in the "e" variable.
    • The substring of the original string "Python" from the second character to the second to last character (using slicing).
    • The first character stored in the "s" variable.
  • Finally, the program prints both the original string "Python" and the modified string "res" to the console.

Source Code

"""
str = "Python"
print("Before Swap :",str)
res = str[-1:] + str[1:-1] + str[:1]
print("After Swap :",res)
"""
str = "Python"
print("Before Swap :",str)
s = str[0]
e = str[-1]
res = e + str[1:-1] + s
print("After Swap :",res)

Output

Before Swap : Python
After Swap : nythoP


Example Programs