Python Program to Count the Occurrences of Each Word in a String

This is a Python Program to accept a hyphen separated sequence of words as input and print the words in a hyphen-separated sequence after sorting them alphabetically.

Problem Description

The program accepts a hyphen separated sequence of words as input and print the words in a hyphen-separated sequence after sorting them alphabetically.

Problem Solution

1. Take a hyphen separated sequence of words from the user.
2. Split the words in the input with hyphen as reference and store the words in a list.
3. Sort the words in the list.
4. Join the words in the list with hyphen between them and print the sorted sequence.
5. Exit.

Program/Source Code

Here is source code of the Python Program to accept a hyphen separated sequence of words as input and print the words in a hyphen-separated sequence after sorting them alphabetically. The program output is also shown below.

print("Enter a hyphen separated sequence of words:")
lst=[n for n in raw_input().split('-')]  
lst.sort()
print("Sorted:")
print('-'.join(lst))
Program Explanation

1. User must enter a hyphen separated sequence of words as the input.
2. The sequence is split with the hyphen as the key and the words are stored in a list.
3. The words in the list are sorted alphabetically using the sort() function.
4. The words in the list are then joined using hyphen as the reference.
6. The sorted sequence of words is then printed.

advertisement
advertisement
Runtime Test Cases
 
Case 1:
red-green-blue-yellow
Sorted:
blue-green-red-yellow
 
Case 2:
Enter a hyphen separated sequence of words:
Bangalore-hyderabad-delhi
Sorted:
Bangalore-delhi-hyderabad

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.