Rearranging the letters of a string in alphabetical order in Python

Hello learners, in this tutorial, we are going to learn some methods to rearrange the letters of a string in alphabetical order in Python. There are many ways to do that. Let’s discuss them one by one.

When all letters are uppercase or all are lowercase

When all the characters in a string are of the same case, then rearranging the letters in alphabetical order is the same as sorting the string. Let’s see how this can be done.

Method #1

We can use the built-in sorted() method on the given string. This method returns the list of letters that are in sorted order. We can use join() method to again form a string from these letters. See the below code to understand it.

s = 'codespeedy'
rearranged_str = ''.join(sorted(s))
print(rearranged_str)

Output:

cddeeeopsy

Use the strip() function if the given string contains spaces. Have a look at the below example.

s = 'MY NAME IS KHAN'
rearranged_str = ''.join(sorted(s)).strip()
print(rearranged_str)

Output:

AAEHIKMMNNSY

Method #2

This method is similar to the above-mentioned method. The only difference is that here we are using a lambda expression with reduce() function to join the string. See the code.

from functools import reduce

s = 'MY NAME IS KHAN'
rearranged_str = reduce(lambda x, y : x + y, (sorted(s))).strip()
print(rearranged_str)

Output:

AAEHIKMMNNSY

When the string contains both uppercase and lowercase letters

When the given input string contains both uppercase and lowercase letters, we can use the following Python code to arrange them alphabetically. Have a look at the given example.

from functools import reduce

s = 'My Name Is Khan'
rearranged_str = ''.join(sorted(s, key = lambda x: x.upper())).strip()
print(rearranged_str)

Output:

aaehIKMmNnsy

Thank you.

Also read: Python reduce() function

Leave a Reply

Your email address will not be published. Required fields are marked *