Here’s a Python program that sorts the words alphabetically in a string provided by the user:
Approach 1:
# Python program to sort words alphabetically in a string # input string string = input("Enter a string: ") # split the string into words words = string.split() # sort the words alphabetically sorted_words = sorted(words) # print the sorted words print("Sorted words in the string: ") for word in sorted_words: print(word)
In this program, we first ask the user to input a string. We then split the string into words using the split()
method, which splits the string at whitespace characters and returns a list of words.
We then sort the words alphabetically using the sorted()
function, which takes a list as input and returns a new sorted list. We store the sorted words in a variable called sorted_words
.
Finally, we print the sorted words using a for loop that iterates through the sorted_words
list and prints each word on a separate line.
Approach 2: With Function
# Function to sort words alphabetically in a string def sort_words(string): # split the string into words words = string.split() # sort the words alphabetically sorted_words = sorted(words) # return the sorted words as a list return sorted_words # input string string = input("Enter a string: ") # call the function and print the results sorted_words = sort_words(string) print("Sorted words in the string: ") for word in sorted_words: print(word)
In this program, we define a function called sort_words
that takes a string as input and returns a list of words sorted alphabetically. The implementation of the function is similar to the previous program, except that instead of printing the sorted words, we return them as a list.
We then ask the user to input a string and call the sort_words
function with the string as input. We store the returned list of sorted words in a variable called sorted_words
.
Finally, we print the sorted words using a for loop that iterates through the sorted_words
list and prints each word on a separate line.