How to Sort a String in Python
Updated on 03rd Jan, 24 9.1K Views

In this guide, we’ll explore various techniques to sort a string in Python. Whether you’re dealing with alphabetical characters, numbers, or even custom-defined orders, Python’s versatility and built-in functions make the process straightforward and flexible.

We are going to discuss the following topics:

Check out this YouTube video to learn about Python:

What is Sorting a String in Python?

Sorting a string in Python refers to the process of rearranging the characters within a string in a specific order, such as ascending (from smallest to largest) or descending (from largest to smallest). This operation is essential in programming languages and is used in a wide range of applications, including data analysis, text processing, and various algorithmic tasks.

Python provides several methods and functions that allow you to efficiently sort strings. These methods offer flexibility in how you can arrange the characters in a string, catering to different requirements and scenarios. Let us now explore the various methods that are required to sort a string in Python.

To learn this latest programming language, sign up for Intellipaat’s trending Python Course and become proficient in it!

Various Methods to Sort a String in Python

These are various methods to sort a string in Python, each with its own approach and efficiency. Depending on the specific requirements of your task, you can choose the most suitable method.

1. Using join() and sorted()

This method combines the join() function with the sorted() function. First, sorted() arranges the characters of the input string in alphabetical order. Then, join() joins these sorted characters back into a single string.

Example:

def sort_string_with_join(input_string):
    sorted_string = ''.join(sorted(input_string))
    return sorted_string
input_string = "intellipaat"
sorted_result = sort_string_with_join(input_string)
print(sorted_result)
Output:
aaeiillnptt 

Explanation:

The above code defines a function called sort_string_with_join that sorts the characters of a given string using the sorted() function and then joins them back into a single string using join(). The sorted string is returned and printed. In this specific example, the input string “intellipaat” is sorted to “aaeiillnptt”.

2. Using the Native Method

In this method, we sort the characters in the input string using the sorted() function. Then, we combine these sorted characters using join(), resulting in the final sorted string.

Example:

def sort_string_native(input_string):
    sorted_string = ''.join(sorted(input_string))
    return sorted_string
input_string = "intellipaat"
sorted_result = sort_string_native(input_string)
print(sorted_result)
Output:
aaeiillnptt 

Explanation:

The provided code defines a function called sort_string_native which sorts the characters of a given string using the sorted() function, and then joins them back into a single string using join(). The sorted string is returned and printed. In this specific example, the input string “intellipaat” is sorted to “aaeiillnptt”.

Want to know about the real-world uses of Python? Read our detailed blog on Python Applications now.

3. Using the sorted function with reduce() and lambda

In this method, the sorted() function is employed to sort the characters of the input string. The reduce() function combines the sorted characters back into a single string using a lambda function. reduce() takes a function (in this case, a lambda function that concatenates two strings) and applies it cumulatively to the elements of a sequence.

Example:

from functools import reduce
def sort_string_with_reduce(input_string):
    sorted_string = reduce(lambda x, y: x + y, sorted(input_string))
    return sorted_string
input_string = "intellipaat"
sorted_result = sort_string_with_reduce(input_string)
print(sorted_result)
Output:
aaeiillnptt 

Explanation:

In the above code, we have defined a function called sort_string_with_reduce that sorts the characters of a given string using the sorted() function. Then, it uses the reduce() function along with a lambda function to concatenate the sorted characters. The sorted string is returned and printed. In this specific example, the input string “intellipaat” is sorted to “aaeiillnptt”.

4. Using Bubble Sort

Bubble sort is a simple sorting algorithm in data structure that repeatedly steps through the list of characters, compares adjacent elements, and swaps them if they are in the wrong order. This process is repeated until the list is sorted.

Example:

def bubble_sort(input_string):
    n = len(input_string)
    string_list = list(input_string)
    for i in range(n-1):
        for j in range(0, n-i-1):
            if string_list[j] > string_list[j+1]:
                string_list[j], string_list[j+1] = string_list[j+1], string_list[j]
    sorted_string = ''.join(string_list)
    return sorted_string
input_string = "intellipaat"
sorted_result = bubble_sort(input_string)
print(sorted_result)
Output:
aaeiillnptt 

Explanation:

The code provided above defines a function called bubble_sort, which applies the bubble sort algorithm to sort the characters of a given string. It then joins these sorted characters back into a single string using the join() function. The sorted string is returned and printed. In this specific example, the input string “intellipaat” is sorted to “aaeiillnptt”.

Also, Check our blog on Conversion of List to String in Python by 4 Methods

5. Using the Merge Sort Method 

Merge sort is a recursive algorithm that divides the input string into smaller subproblems, sorts them separately, and then merges them back together. It’s a divide-and-conquer strategy that is highly efficient for sorting.

Example:

def merge_sort(input_string):
    if len(input_string) <= 1:
        return input_string
    def merge(left, right):
        result = []
        i = j = 0
        while i < len(left) and j < len(right):
            if left[i] < right[j]:
                result.append(left[i])
                i += 1
            else:
                result.append(right[j])
                j += 1
        result.extend(left[i:])
        result.extend(right[j:])
        return result
    mid = len(input_string) // 2
    left = input_string[:mid]
    right = input_string[mid:]
    return merge(merge_sort(left), merge_sort(right))
input_string = "intellipaat"
sorted_result = ''.join(merge_sort(input_string))
print(sorted_result)
Output:
aaeiillnptt 

Explanation:

The above code defines a function called merge_sort, which is a recursive sorting algorithm. It divides the input string into smaller segments, sorts them separately, and then merges them back together. The sorted string is returned and printed. In this specific example, the input string “intellipaat” is sorted to “aaeiillnptt”.

6. Using a Dictionary

In this method, a dictionary is used to count the frequency of each character in the input string. The keys of the dictionary are then sorted, and the characters are concatenated based on their sorted order and frequency.

Example:

def sort_string_with_dict(input_string):
    char_freq = {}
    for char in input_string:
        if char in char_freq:
            char_freq[char] += 1
        else:
            char_freq[char] = 1
    sorted_string = ''.join([char * char_freq[char] for char in sorted(char_freq.keys())])
    return sorted_string
input_string = "intellipaat"
sorted_result = sort_string_with_dict(input_string)
print(sorted_result)
Output:
aaeiillnptt 

Explanation:

The presented code defines a function called sort_string_with_dict, which sorts the characters of a given string using a dictionary to count the frequency of each character. It then uses list comprehensions and join() to concatenate the sorted characters. The sorted string is returned and printed. In this specific example, the input string “intellipaat” is sorted to “aaeiillnptt “.

Prepare yourself for the industry by going through Python Interview Questions and Answers now!

Conclusion

With the growing importance of data science and machine learning, optimizing string sorting can have a significant impact on the performance of various algorithms and models. Additionally, advancements in hardware and parallel processing capabilities may lead to even faster sorting methods, providing developers with more powerful tools to handle large datasets efficiently.

If you have any doubts, you can reach out to us on our Python Community!

Course Schedule

Name Date Details
Python Course 24 Feb 2024(Sat-Sun) Weekend Batch
View Details
Python Course 02 Mar 2024(Sat-Sun) Weekend Batch
View Details
Python Course 09 Mar 2024(Sat-Sun) Weekend Batch
View Details

Leave a Reply

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

Speak to our course Advisor Now !

Related Articles

Subscribe to our newsletter

Signup for our weekly newsletter to get the latest news, updates and amazing offers delivered directly in your inbox.