Python Program to Sort Words in Alphabetical Order

Python Program to Sort Words in Alphabetical Order

Let's create a simple tutorial on how to sort words in a string in alphabetical order.

Sorting Words in Alphabetical Order

Step 1: Get the input string from the user.

input_string = input("Enter a string: ") 

Step 2: Split the string into words. We will use the split() method to break the string into a list of words.

words = input_string.split() 

Step 3: Sort the list of words.

words.sort() 

Step 4: Join the sorted words back into a string.

sorted_string = ' '.join(words) 

Step 5: Display the sorted string.

print("The sorted string is:", sorted_string) 

Here's the complete program combining all these steps:

# Get the input string from the user input_string = input("Enter a string: ") # Split the string into words words = input_string.split() # Sort the list of words words.sort() # Join the sorted words back into a string sorted_string = ' '.join(words) # Display the sorted string print("The sorted string is:", sorted_string) 

Example:

Enter a string: python is an awesome language The sorted string is: an awesome is language python 

This program will sort the words in a string in alphabetical order. Note that this approach considers a word as a sequence of characters separated by spaces, so punctuations attached to words will be considered as part of those words. If you need a more sophisticated sorting mechanism that ignores punctuations, additional processing will be required.


More Tags

google-signin heap-memory numeric flying-saucer windows-runtime macos uiviewcontroller top-n pagerslidingtabstrip lazy-evaluation

More Programming Guides

Other Guides

More Programming Examples