Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python | Ways to sort letters of string alphabetically

  • Difficulty Level : Easy
  • Last Updated : 11 May, 2020

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

Examples:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

Input : PYTHON
Output : HNOPTY

Input : Geeks
Output : eeGks

When string is in same case –

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






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

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




# 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))
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.




# 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))
Output:
HNOPTY

When string is in different cases –

Using sorted() with join()




# 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))
Output:
eeGks



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!