Python: How to Sort a String

Do The Thing
2 min readJan 10, 2023

--

Sorting a string in Python can be a useful operation in a variety of situations. For instance, you might want to sort a list of words alphabetically, or you might want to sort a list of names by last name. In this post, we will take a look at how to sort a string in Python.

Method 1: Using the sorted() Function

The first way to sort a string in Python is by using the built-in sorted() function. This function takes an iterable (such as a list, tuple, or string) and returns a new sorted list with the elements in ascending order.

Here is an example of how to use the sorted() function to sort a string:

# define the string
my_string = "python"
# use the sorted function to sort the string
sorted_string = sorted(my_string)

# print the sorted string
print(sorted_string)

Output:

['h', 'n', 'o', 'p', 't', 'y']

As you can see, the sorted() function returns a new list with the characters of the string in ascending order.

Method 2: Using the join() and sort() Methods

Another way to sort a string in Python is by using the join() and sort() methods. This method involves first converting the string into a list of characters, sorting the list, and then using the join() method to convert the list back into a string.

Here is an example of how to use the join() and sort() methods to sort a string:

# define the string
my_string = "python"
# convert the string into a list and sort it
sorted_list = sorted(list(my_string))

# use the join method to convert the list back into a string
sorted_string = ''.join(sorted_list)

# print the sorted string
print(sorted_string)

Output:

hnopty

As you can see, this method also returns a new string with the characters in ascending order.

Conclusion

In this post, we looked at two ways to sort a string in Python: using the sorted() function and using the join() and sort() methods. Both methods allow you to easily sort a string in ascending order, and can be useful in a variety of situations.

--

--

Do The Thing
Do The Thing

No responses yet