Skip to content
Related Articles

Related Articles

Python program to sort a string

View Discussion
Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 06 Jun, 2022
View Discussion
Improve Article
Save Article

Sorting has always been quite a popular utility with lots of applications everywhere, where Python language opts. Python in its language offers a sort function to perform this task. But due to fact that not all the containers in Python are mutable, such as string, the sort function doesn’t work as it is in place tries to sort and immutability stops this. Let’s discuss certain ways in which a string can be sorted. 

Method #1 : join() + sorted()

 The combination of the above functions can potentially solve this particular problem. This task is performed in 2 steps in which first step we get the sorted list of characters and then we join the result to get the resultant sorted string. 

Example

Python3




# Python3 code to demonstrate
# Sorting a string
# using join() + sorted()
 
# initializing string
test_string = "geekforgeeks"
 
# printing original string
print("The original string : " + str(test_string))
 
# using join() + sorted()
# Sorting a string
res = ''.join(sorted(test_string))
     
# print result
print("String after sorting : " + str(res))

Output : 

The original string : geekforgeeks
String after sorting : eeeefggkkors

Method #2: Quick Ninja Method

To sort a given string with user input using the inbuilt python sort method.

Example

Python3




string = input("Enter String: ")
lst = [string[i] for i in range(0,len(string))]
lst.sort()
for i in lst:
    print(i, end = "")

Output:

Enter String: geeksforgeeks
eeeefggkkors

Method #3 : Using sorted() + reduce() + lambda 

This particular task can also be performed using the combination of the above 3 functions. Here we join the resultant sorted list of characters using the lambda function joined by the reduce function. Works only for Python2 

Example

Python




# Python code to demonstrate
# Sorting a string
# using sorted() + reduce() + lambda
 
# initializing string
test_string = "geekforgeeks"
 
# printing original string
print("The original string : " + str(test_string))
 
# using sorted() + reduce() + lambda
# Sorting a string
res = reduce(lambda x, y: x + y, sorted(test_string))
     
# print result
print("String after sorting : " + str(res))

Output : 

The original string : geekforgeeks
String after sorting : eeeefggkkors

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!