Last Updated on May 6, 2024 by Roshan Parihar
To sort strings in alphabetical order in Python, use the string as the argument of the sorted()
and place them inside the join()
function.
You can also use the reduce()
and the accumulate()
functions of Python for sorting a string. Let’s find out with the different examples given below.
How to Sort String in Alphabetical Order Using join() with sorted() in Python?
If you want to sort the string in alphabetical order in Python, you can use the sorted()
function and pass the string variable as its argument. After that, place them inside the join()
function as an argument.
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 characters in a proper sequence alphabetically. It sorts the strings alphabetically in ascending order (a to z & A to Z).
Using reduce() with sorted() for Sorting String Alphabetically 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.
Using accumulate() with 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 arranged in proper alphabetical order.