Python Tutorials

Python Programs

Python Sort Words in Alphabetic Order


Python Sort Words in Alphabetic Order

In this tutorial, we will learn how to sort words in alphabetic order in Python. We will cover the basic concept of string manipulation and implement a function to perform the sorting.


What is String Manipulation

String manipulation involves altering, parsing, and analyzing strings in various ways. Sorting words in a string alphabetically is a common task in text processing.


Syntax

The syntax to sort words in alphabetic order in Python is:

def sort_words(s):
    words = s.split()
    words.sort()
    return ' '.join(words)


Sorting words in alphabetic order

We can create a function to sort words in a given string alphabetically by splitting the string into words, sorting the list of words, and then joining them back into a string.

For example,

  1. Define a function named sort_words that takes one parameter s.
  2. Use the split method to break the string into a list of words.
  3. Use the sort method to sort the list of words alphabetically.
  4. Use the join method to join the sorted list of words back into a single string.
  5. Return the sorted string.
  6. Call the function with a sample string and print the result.

Python Program

def sort_words(s):
    words = s.split()
    words.sort()
    return ' '.join(words)

# Sample string
sample_string = "hello world welcome to python programming"

# Sort words in the sample string
result = sort_words(sample_string)

# Print the result
print('Sorted words:', result)

Output

Sorted words: hello programming python to welcome world