Sort Letters in a String in Python

The easiest way to sort letters is to use the join and sorted functions together.

If you execute this code, you are going to get this result:


Let’s analyze the code. We are going to use only the sorted function for now and see what it does.

The sorted function split a string into a sorted list of characters.

['g', 'i', 'n', 'r', 's', 't']

The join function can be used with a string. Therefore you have to use a string variable or like in our case, an empty string to join these letters into a single string.

Sort letters with duplicates

Take a look at an example where there are duplicates and space.

After you print the result, the space is at the beginning, and the uppercase letters are in the front of lowercase letters.

Keep unique values only

It’s very easy to get unique values from the string. Sets are used to get an unordered collection of unique elements.

See what happens if you convert the string to a set:

You are going to get unique letters from the string:

{'e', 'u', 'g', 'B', 'l', ' ', 'm', 'b'}

Sort and join this set to get distinct values only.

The result:


Don’t keep all uppercase letters at the beginning

In the previous example, the uppercase letter moved at the beginning of a string. But all uppercase letters move before lowercase in that code.

Take a look:

The letter “G” goes before “b”. If this is what you want, you can use this code.


If you want “G” to go after “b” use this code:

It will sort all letters alphabetically, without keeping the uppercase at the beginning.


Keep only letters

This code will return only uppercase and lowercase letters.

No numbers, no spaces, no punctuation marks, and no numbers – only letters: