Given a String. The task is to swap the first and the last character of the string.
Input: GeeksForGeeks Output: seeksForGeekG Input: Python Output: nythoP
Python string is immutable which means we cannot modify it directly. But Python has string slicing which makes it very easier to perform string operations and make modifications. Follow the below steps to swap characters –
- We initialize a variable start, which stores the first character of the string (string)
- We initialize another variable end that stores the last character (string[-1])
- Then we will use string slicing, string[1:-1], this will access all the characters from the 2nd position excluding the last character.
- Then we add these three as required forming a new string that has the first and last characters of the original string swapped. And then we will print it.
Below is the implementation.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.