How to sort the letters in a string alphabetically in Python?


In this article, we are going to find out how to sort the letters in a string alphabetically in Python.

The first approach is by using sorted() and join() methods. We send a string as input and we get alphabetically sorted string as output. We need to send the string as parameter to the sorted() method and after that we can join them using the join() method.

The sorted() method returns a list after ordering the items of an iterable in either ascending or descending order.

Example 1

In the example given below, we are taking a string as input and we are sorting the string in ascending order using sorted() and join() methods 

str1 = "tutorialspoint"

print("The given string is")
print(str1)

print("Sorting the string in ascending order")
res = ''.join(sorted(str1))
print(res)

Output

The output of the above example is as follows −

The given string is
tutorialspoint
Sorting the string in ascending order
aiilnooprstttu

Example 2

In the example given below, we are taking the same code as above but here we are going to sort the string that has mixed casing 

str1 = "TutorialsPoint"

print("The given string is")
print(str1)

print("Sorting the string in ascending order")
res = ''.join(sorted(str1))
print(res)

Output

The output of the above example is as shown below −

The given string is
TutorialsPoint
Sorting the string in ascending order
PTaiilnoorsttu

Using sorted() and sets

The second approach is by using sorted() method and sets. This is similar to the above approach, but this is used if you want to have only Unique characters as output. We just need to send the string as a set.

Example

In the example given below, we are taking a string as input and we are sorting the unique characters 

str1 = "TutorialsPoint"

print("The given string is")
print(str1)

print("Sorting the string in ascending order")
res = ''.join(sorted(set(str1)))
print(res)

Output

The output of the above example is given below −

The given string is
TutorialsPoint
Sorting the string in ascending order
PTailnorstu

Updated on: 07-Dec-2022

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements