How to Sort a String in Python?

Deepsandhya Shukla 07 Feb, 2024 • 3 min read

Introduction

Sorting a string in Python refers to arranging the characters of a string in a specific order. This can be done in various ways, depending on the requirements and the desired outcome. In this article, we will explore different approaches to sort a string in Python and discuss their performance analysis. We will also provide examples and code snippets to demonstrate the implementation of each approach.

Different Approaches to Sort a String in Python

Using the sorted() Function

The sorted() function in Python is a built-in function that can be used to sort any iterable, including strings. It takes an iterable as input and returns a new sorted list. To sort a string using this approach, we can convert the string into a list of characters, sort the list using the sorted() function, and then join the sorted characters back into a string.

Example:

string = "python"

sorted_string = ''.join(sorted(string))

print(sorted_string)

Output:

hnopty

Implementing Bubble Sort Algorithm

Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. This process is repeated until the list is sorted. We can implement the bubble sort algorithm to sort a string by considering the ASCII values of the characters.

Example:

def bubble_sort(string):

    n = len(string)

    for i in range(n):

        for j in range(0, n-i-1):

            if ord(string[j]) > ord(string[j+1]):

                string[j], string[j+1] = string[j+1], string[j]

    return string

string = "python"

sorted_string = bubble_sort(list(string))

print(''.join(sorted_string))

Output:

hnopty

Utilizing the sort() Method of Lists

In Python, lists have a built-in sort() method that can be used to sort the elements in ascending order. To sort a string using this approach, we can convert the string into a list of characters, sort the list using the sort() method, and then join the sorted characters back into a string.

Example:

string = "python"

sorted_string = sorted(list(string))

print(''.join(sorted_string))

Output:

hnopty

Creating a Custom Sorting Function

Python provides the flexibility to create custom sorting functions using the key parameter of the sorted() function. This allows us to define our own criteria for sorting a string. For example, we can sort a string based on the length of its words or the frequency of characters.

Example:

string = "python programming is fun"

sorted_string = ' '.join(sorted(string.split(), key=len))

print(sorted_string)

Output:

is fun python programming

Also Read: 90+ Python Interview Questions to Prepare Before Your Next Interview

Examples of Sorting a String in Ascending Order

To sort a string in ascending order, we can use any of the approaches mentioned above. Here’s an example using the sorted() function:

string = "python"

sorted_string = ''.join(sorted(string))

print(sorted_string)

Output:

hnopty

Sorting a String in Descending Order

To sort a string in descending order, we can use the sorted() function with the reverse parameter set to True. Here’s an example:

string = "python"

sorted_string = ''.join(sorted(string, reverse=True))

print(sorted_string)

Output:

ytpnoh

Sorting a String Ignoring Case Sensitivity

To sort a string while ignoring the case sensitivity of the characters, we can convert the string to lowercase or uppercase before sorting. Here’s an example:

string = "Python"

sorted_string = ''.join(sorted(string, key=str.lower))

print(sorted_string)

Output:

hnoPty

Want to learn Python for FREE? Enroll in our Introduction to Python Program today!

Best Practices for Sorting Strings in Python

Handling Edge Cases and Invalid Inputs

When sorting strings in Python, it is important to handle edge cases and invalid inputs. For example, if the string is empty or contains only whitespace, it should be handled separately. Additionally, if the input is not a string, appropriate error handling should be implemented.

Considering Efficiency and Scalability

While sorting strings, it is important to consider the efficiency and scalability of the chosen approach. For large strings or performance-critical applications, it is recommended to use sorting algorithms with better time complexity, such as the sorted() function or the sort() method of lists.

Writing Clean and Readable Code

When writing code to sort strings, it is important to follow best practices for clean and readable code. This includes using meaningful variable names, adding comments to explain the logic, and breaking down complex operations into smaller, more manageable steps.

Conclusion

Sorting a string in Python can be achieved using various approaches, such as the sorted() function, join() method with sorted characters, bubble sort algorithm, sort() method of lists, and custom sorting functions. Each approach has its own advantages and performance characteristics. By understanding these approaches and considering best practices, developers can efficiently sort strings in Python based on their specific requirements.

Become a python expert with our FREE Introduction to Python Program!

Frequently Asked Questions

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Responses From Readers

Clear

Related Courses

image.name
0 Hrs 70 Lessons
5

Introduction to Python

Free