Last Updated on July 6, 2021 by Roshan Parihar
In this tutorial, learn how to sort string in alphabetical order in Python. The short answer is to use the string as the argument of the sorted()
and place them inside the join()
.
You can also use the reduce()
and the accumulate()
functions of Python for sorting a string in Python. Let’s find out with the different examples given below.
Method 1: Using join() with sorted() to Sort String Alphbatically in Python
To sort the string in alphabetical order, you have to use the sorted()
function and pass the string variable as its argument. After that, place them inside the join()
function as the argument of it. See the example below to learn the method.
1 2 3 4 5 6 7 8 |
#Declare string in Python myString = 'string'; #Sort string using join() and sorted() sortStr = ''.join(sorted(myString)) #Print result print(sortStr) |
Output
The above example shows the use of the function that arranges the string character in proper sequence alphabetically. It sorts the strings alphabetically in ascending order (a to z & A to Z).
Method 2: Using reduce() with sorted() to Sort String in Alphabetical Order in Python
When you want to sort the string alphabetically, you can use the reduce()
function. Inside that function, you have to use the sorted()
with the string variable as its argument.
1 2 3 4 5 6 7 8 9 10 11 |
#Import the required library from functools import reduce #Declare string in Python myString = 'string'; #Sort string using join() and sorted() sortStr = reduce(lambda x,y: x+y, sorted(myString)) #Print result print(sortStr) |
Output
The above example contains the same output that you have got in the first example above.
Method 3: Using accumulate() and sorted() in Python
In addition to the above methods, you can also use the accumulate()
function that takes the sorted()
as its argument. Also, pass the string variable as the argument of the sorted()
function in Python.
After that, you have to use the tuple()
function to convert the result into a string in Python. You can check the below example to get the use of the method.
1 2 3 4 5 6 7 8 9 10 11 |
#Import the required library from itertools import accumulate #Declare string in Python myString = 'string'; #Sort string using join() and sorted() sortStr = tuple(accumulate(sorted(myString)))[-1] #Print result print(sortStr) |
Output
The output given in the above example is the string arranges in proper alphabetical order.