This is a Python Program to form a string where the first character and the last character have been exchanged.
The program takes a string and swaps the first character and the last character of the string.
1. Take a string from the user and store it in a variable.
2. Pass the string as an argument to a function.
3. In the function, split the string.
4. Then add the last character to the middle part of the string which is in turn added to the first character.
5. Print the modified string.
6. Exit.
Here is source code of the Python Program to form a string where the first character and the last character have been exchanged. The program output is also shown below.
def change(string): return string[-1:] + string[1:-1] + string[:1] string=raw_input("Enter string:") print("Modified string:") print(change(string))
1. User must enter a string and store it in a variable.
2. This string is passed as an argument to a function.
3. In the function, using string slicing, the string is first split into three parts which is the last character, middle part and the first character of the string.
4. These three parts are then concatenated using the ‘+’ operator.
5. The modified string is then printed.
Case 1: Enter string:abcd Modified string: dbca Case 2: Enter string:hello world Modified string: dello worlh
Sanfoundry Global Education & Learning Series – Python Programs.
To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.
- Practice Programming MCQs
- Check Information Technology Books
- Apply for Programming Internship
- Apply for Python Internship
- Check Python Books