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 –
Below is the implementation.
def swap(string): # storing the first character start = string[0] # storing the last character end = string[-1] swapped_string = end + string[1:-1] + start print(swapped_string) # Driver Code swap("GeeksforGeeks") swap("Python")
Output:
seeksforGeekG nythoP
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.