The easiest way to sort letters is to use the join and sorted functions together.
1 2 |
my_string = 'string' print(''.join(sorted(my_string))) |
If you execute this code, you are going to get this result:
ginrst
Let’s analyze the code. We are going to use only the sorted function for now and see what it does.
1 2 |
my_string = 'string' print(sorted(my_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.
1 2 |
my_string = 'BubBle gum' print(''.join(sorted(my_string))) |
After you print the result, the space is at the beginning, and the uppercase letters are in the front of lowercase letters.
1 |
BBbeglmuu |
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:
1 2 |
my_string = 'BubBle gum' print(set(my_string)) |
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.
1 2 |
my_string = 'BubBle gum' print(''.join(sorted(set(my_string)))) |
The result:
Bbeglmu
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:
1 2 |
my_string = 'BubBle Gum!' print(''.join(sorted(set(my_string)))) |
The letter “G” goes before “b”. If this is what you want, you can use this code.
!BGbelmu
If you want “G” to go after “b” use this code:
1 2 |
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.
!BbeGlmu
Keep only letters
This code will return only uppercase and lowercase letters.
1 2 |
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:
bBeGlmu