w3resource

Python Exercise: Accept a hyphen-separated sequence of words as input and prints the sorted words


15. Sort Hyphen-Separated Sequence of Words Alphabetically

Write a Python program that accepts a hyphen-separated sequence of words as input and prints the words in a hyphen-separated sequence after sorting them alphabetically.

Sample Solution:

Python Code:

# Take user input and split it into a list based on the hyphen ("-") separator, creating a list named 'items'
items = [n for n in input().split('-')]

# Sort the elements in the 'items' list in lexicographical order (alphabetical and numerical sorting)
items.sort()

# Join the sorted elements in the 'items' list using the hyphen ("-") separator and print the resulting string
print('-'.join(items)) 

Sample Output:

green-red-black-white                                                                                         
black-green-red-white 

Explanation:

In the exercise above the code takes user input, splits it based on the hyphen -, and stores the parts in a list called 'items'. It then sorts these items in lexicographical order (ascending order for text strings and numerical order for numbers). Finally, it joins the sorted items using the hyphen - as a separator and prints the resulting string.

Pictorial presentation:

Python exercises: Accept a hyphen-separated sequence of words as input and prints the sorted words.

Flowchart:

Flowchart: Python exercises: Accept a hyphen-seperated sequence of words as input and prints the sorted words.

For more Practice: Solve these Related Problems:

  • Write a Python program that splits a hyphen-separated string into a list, sorts the list, and joins it back into a hyphen-separated string.
  • Write a Python program to reverse the order of words in a hyphen-separated string and then sort them alphabetically.
  • Write a Python program to implement a function that takes hyphen-separated words and returns them sorted, handling duplicate words gracefully.
  • Write a Python program to use regular expressions to split a hyphen-separated string, sort the words, and then reassemble the string.

Go to:


Previous: Write a Python function to check whether a string is a pangram or not.
Next: Write a Python function to create and print a list where the values are square of numbers between 1 and 30 (both included).

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.