Python Program to Sort Hyphen Separated Sequence of Words in Alphabetical Order

This is a Python Program to form a string where the first character and the last character have been exchanged.

Problem Description

The program takes a string and swaps the first character and the last character of the string.

Problem Solution

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.

Program/Source Code

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))
Program Explanation

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.

advertisement
advertisement
Runtime Test Cases
 
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.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.