Python Program to swap the First and the Last Character of a string
Last Updated :
23 Mar, 2023
Given a String. The task is to swap the first and the last character of the string.
Examples:
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[0])
- 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 of the above approach:
Python3
def swap(string):
start = string[ 0 ]
end = string[ - 1 ]
swapped_string = end + string[ 1 : - 1 ] + start
print (swapped_string)
swap( "GeeksforGeeks" )
swap( "Python" )
|
Output
seeksforGeekG
nythoP
Time Complexity: O(k), as string slicing takes O(k)
Auxiliary Space: O(n)
Method : Using lists without slicing
Python3
string = "GeeksforGeeks"
x = list (string)
temp = x[ 0 ]
x[ 0 ] = x[ - 1 ]
x[ - 1 ] = temp
print ("".join(x))
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 3: Using the built-in function join() and list comprehension.
Step-by-step approach:
- Convert the given string into a list of characters using list comprehension.
- Swap the first and last character by indexing the first and last elements and assigning them to the opposite positions.
- Convert the list of characters back into a string using join().
Below is the implementation of the above approach:
Python3
def swap(string):
char_list = [char for char in string]
char_list[ 0 ], char_list[ - 1 ] = char_list[ - 1 ], char_list[ 0 ]
swapped_string = ''.join(char_list)
print (swapped_string)
swap( "GeeksforGeeks" )
swap( "Python" )
|
Output
seeksforGeekG
nythoP
Time complexity: O(n) where n is the length of the given string. This is because we need to iterate over each character of the string to convert it into a list of characters and then back to a string.
Auxiliary space: O(n) where n is the length of the given string. This is because we are creating a new list of characters to store the characters of the given string.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...