Python | Ways to sort letters of string alphabetically

Given a string of letters, write a python program to sort the given string in an alphabetical order.

Examples:

Input : PYTHON
Output : HNOPTY

Input : Geeks
Output : eeGks

When string is in same case –

Method #1 : Using sorted() with join()

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to sort letters 
# of string alphabetically
  
def sortString(str):
    return ''.join(sorted(str))
      
# Driver code
str = 'PYTHON'
print(sortString(str))

chevron_right


Output:

HNOPTY

 
Method #2 : Using sorted() with accumulate()

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to sort letters 
# of string alphabetically
from itertools import accumulate
  
def sortString(str):
    return tuple(accumulate(sorted(str)))[-1]
      
# Driver code
str = 'PYTHON'
print(sortString(str))

chevron_right


Output:

HNOPTY

 
Method #3 : Using sorted() with reduce()

Another alternative is to use reduce() method. It applies a join function on the sorted list using ‘+’ operator.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to sort letters 
# of string alphabetically
from functools import reduce
  
def sortString(str):
    return reduce(lambda a, b : a + b, sorted(str))
      
# Driver code
str = 'PYTHON'
print(sortString(str))

chevron_right


Output:

HNOPTY

When string is in different cases –

Using sorted() with join()

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to sort letters 
# of string alphabetically
from itertools import accumulate
  
def sortString(str):
    return "".join(sorted(str, key = lambda x:x.lower()))
      
# Driver code
str = 'Geeks'
print(sortString(str))

chevron_right


Output:

eeGks


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.