Skip to content

Python: Sort a String (4 Different Ways)

Python Sort String with Sorted Cover image

In this tutorial, you’ll learn how to use Python to sort a string in alphabetical order. You’ll learn a number of different ways to do this, including sorting the strings in alphabetical order, regardless of case and being mindful of case. You’ll also learn how to sort unique characters and how to sort the string while removing whitespace and punctuation.

Being able to work with Python strings and knowing how to sort them has many useful applications in Python. For example, you could be checking for duplicate strings to trim your data prior to doing natural language processing. Alternatively, you could be building a game and need to check for anagrams in your program.

The Quick Answer: Use “”.join(sorted(a_string, key=str.lower))

Quick Answer - Python Sort String Using Sorted
Use Python to Sort a String Using sorted()

Sort a Python String with Sorted

Python comes with a function, sorted(), built-in. This function takes an iterable item and sorts the elements by a given key. The default value for this key is None, which compares the elements directly. The function returns a list of all the sorted elements.

Let’s see what this looks like:

# Sort a Python String with sorted()
word = 'datagy'

sorted_word = sorted(word)
print(sorted_word)

# Returns: ['a', 'a', 'd', 'g', 't', 'y']

We can see that when we apply the sorted function to our string, a list is returned. The list items are sorted alphabetically.

How can we turn this list back into a string? We can use the str.join() method, as shown below:

# Sort a Python String with sorted()
word = 'datagy'

sorted_word = sorted(word)
sorted_word = ''.join(sorted_word)
print(sorted_word)

# Returns: aadgty

We can see that the string is now sorted (and is back to being a string). We can actually combine this into a single line by writing:

# Sort a Python String with sorted()
word = 'datagy'

sorted_word = ''.join(sorted(word))
print(sorted_word)

# Returns: aadgty

Now, what happens when we include some capitals in our string? Let’s capitalize the first letter and see what happens:

# Sort a Python String with sorted()
word = 'Datagy'

sorted_word = ''.join(sorted(word))
print(sorted_word)

# Returns: Daagty

We can see that now the capital D appears before the lowercase a. Why does this happen? Python interprets the sorting explicitly, when we don’t apply a key, forcing the values to be sorted based on their ASCII values. In this, capital letters are sorted prior to the lowercase values.

In the next section, you’ll learn how to sort a Pythons string without this case sensitivity, which may give you the results you’re looking for.

Want to learn how to reverse a string in Python? Check out this tutorial here, which will teach you six different ways to reverse a Python string: Python: Reverse a String (6 Easy Ways)

Sort a Python String with Sorted without Case Sensitivity

In the example above, you learned how to use the sorted function to a string in Python. However, simply applying the sorted function without a key, results in sorted capital letters before all lowercase letters. What if we wanted to a sort a string with capital letters but place them in alphabetical order? We can use the key= parameter to specify how we can sort a string with case insensitivity.

The key= argument allows us to pass in a function that allows Python to create a comparison key for each element in the iterable. What this means is that we can use the function to create a value to compare against. In the previous example, this was set to the default value of None, which means the values were compared directly against one another.

Let’s see how we can make use of the key= parameter of the sorted function to sort our string, ignoring case sensitivity:

# Sort a Python String with sorted()
word = 'Datagy'

sorted_word = ''.join(sorted(word, key=str.lower))
print(sorted_word)

# Returns: aaDgty

We can see here that, while all the keys in the string remain in their original casing, they are now sorted based on their lowercase equivalents. This is a great way to sort a string while maintaining the integrity of the original string, if capitalization is important.

If you don’t care about the capitalization, you can always convert the string to lowercase. This way, you don’t need to apply the key= parameter. Let’s see what this looks like:

# Sort a Python String with sorted()
word = 'Datagy'

sorted_word = ''.join(sorted(word.lower()))
print(sorted_word)

# Returns: aadgty

We can see here that we used the same string method, .lower(), as we did earlier, to convert our string to lower case. This, of course, changes the values of the string, thereby removing the integrity of the original data.

In the next section, you’ll learn how to sort a string with unique characters only.

Want to learn how to convert a string to lowercase? Learn the nuances of the three different methods that Python offers in this in-depth tutorial: Python Lowercase String with .lower(), .casefold(), and .islower()

Sort a Python String with Unique Characters Only

You may want to simply sort the different characters of a string with unique characters in that string. With this, we can use the Python set function, which we can use to turn an item into a set. Sets are one of the main Python data container structures. One of their unique characteristics is that all the items in them are unique.

We can use the uniqueness to our advantage here – we can turn our string into a set and then sort the values. Finally, we can convert it back to a string using the .join string method.

Let’s see what this looks like:

# Sort a Python String with sorted()
word = 'Datagy'

sorted_word = ''.join(sorted(set(word)))
print(sorted_word)

# Returns: Dagty

We can see here that the string is sorted for unique characters only. If we wanted to sort our characters again using case insensitivity, we can apply the same approach as shown above:

# Sort a Python String with sorted()
word = 'Datagy'

sorted_word = ''.join(sorted(set(word), key=str.lower))
print(sorted_word)

# Returns: aDgty

Since Python strings are often quite messy and may contain whitespace and punctuation. If you want to learn how to sort strings without whitespace and punctuation, check out the next section.

Want to check if a Python string is a palindrome? This tutorial will teach you five different ways to accomplish this: Python: Check If a String is a Palindrome (5 Easy Ways!)

Sort a Python String and Remove White Space and Punctuation

In this final section, you’ll learn how to sort a Python string and remove white space and punctuation. Because Python strings will often contain characters that are not alphabetical, we can find a way to sort our string ignoring these values.

In order to do this, we can first filter our string using the .isalpha string method, which keeps only alphabetical characters. Let’s see how we can do this in Python:

# Sort a Python String with sorted()
word = 'da ta ?gy!'

sorted_word = ''.join(filter(lambda x:x.isalpha(), sorted(word,key=lambda x:x.lower())))

print(sorted_word)

# Returns: aadgty

Let’s see what we’ve done here:

  1. We first sort the word using case insensitivity
  2. We then use the filter function to keep only alphabetical characters
  3. Finally, we join our list of characters back into a single string

Want to learn how to remove all special characters in a Python string? Check out this tutorial to learn how – Python: Remove Special Characters from a String

Conclusion

In this tutorial, you learned how to use Python to sort a string. You learned a number of different ways to do this including how to use the sorted function with and without case sensitivity. You also learned how to sort only unique letters and how to sort only alphabetical characters, thereby removing whitespace and punctuation.

To learn more about the Python sorted function, check out the official documentation here.

Leave a Reply

Your email address will not be published.