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

This Python program sorts a hyphen-separated sequence of words in alphabetical order.

Problem Statement

This version presents the problem statement in a concise and structured manner, making it clear that the program addresses the task of sorting hyphen-separated words alphabetically while maintaining the hyphen separation. The rest of the program remains unchanged.

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

def sort_hyphen_separated_sequence(sequence):
    words = sequence.split('-')
    sorted_words = sorted(words)
    sorted_sequence = '-'.join(sorted_words)
    return sorted_sequence

input_sequence = input("Enter a hyphen-separated sequence of words: ")
sorted_sequence = sort_hyphen_separated_sequence(input_sequence)
print("Sorted sequence:", sorted_sequence)

How it Works

  1. Function Definitions: The program starts by defining a function named sort_hyphen_separated_sequence(sequence) that takes a sequence of hyphen-separated words as input. Inside this function, the sequence is split into individual words using the hyphen as a delimiter. The sorted() function is then used to sort the words alphabetically, and the sorted words are joined back together using hyphens to create the sorted sequence. The sorted sequence is returned by the function.
  2. Main Function: The main() function serves as the entry point of the program. It begins by printing a header to introduce the program’s purpose and functionality.
  3. Input and Sorting: The program prompts the user to input a sequence of hyphen-separated words. The input is stored in the input_sequence variable. The sort_hyphen_separated_sequence() function is called with the input sequence as an argument, and it returns the sorted sequence.
  4. Display: After sorting the sequence, the program displays both the original input sequence and the sorted sequence using the print() function. This allows the user to see how the alphabetical sorting has been applied while maintaining the hyphen separation.
  5. Program Execution: The program execution is initiated by the if __name__ == "__main__": condition. This ensures that the main() function is only executed when the script is run directly, not when it’s imported as a module in another program.

Input/ Output

This Python program sorts a hyphen-separated sequence of words in alphabetical order.

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this python tutorial, you will learn how to Display Prime Numbers Between Two Intervals using the if and else...
In this python tutorial, you will learn how to Calculate Standard Deviation with built in functions of the python programming...
In this Python program, we will convert temperature values from Celsius to Fahrenheit. The Celsius and Fahrenheit scales are two...