Sort letters in a string alphabetically in Python

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

my_string = 'string'

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.

my_string = 'string'

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.

my_string = 'BubBle gum'

After you print the result, 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 string to a set:

my_string = 'BubBle gum'

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.

my_string = 'BubBle gum'

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:

my_string = 'BubBle Gum!'

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


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

my_string = 'BubBle Gum!'
print(''.join(sorted(my_string, key=lambda x: x.lower())))

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.

my_string = 'BubBle Gum 2020!'
print(''.join(filter(lambda x: x.isalpha(), sorted(set(my_string), key=lambda x: x.lower()))))

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