Python program to sort string character in ascending order

Support this post with a reaction:

In this tutorial, we will learn writing the python program to sort all the characters of the string in ascending order.

Problem Statement

We have to take a string from the users as an input. And we have to write program in python which will take input and return the string with sorted characters.

For example:

Case1: If the user inputs the string ‘python’

Then the output should be ‘honpty’, where all the characters are sorted.

Case2: If the user inputs the string ‘quescol’

Then the output should be ‘celoqsu’, where all characters are sorted.

Our logic to sort string in ascending order

  • Our program accepts string as an input from the user.
  • In order to sort the characters of the string, our program will use the python built-in function ‘sorted()’.
  • sorted() function will sort the input string and will return sorted string.

Python code to sort string character in ascending order

#taking input from the user
string = input("Enter the string : ")
#converting string into list of its characters
strList=list(string) 
#sorting elements of list
sortedString=''.join(sorted(strList)) 
print("String Sorted in ascending order :", sortedString)

Output:

Enter the string : quescol
String Sorted in ascending order : celoqsu

Explanation:

For the input string ‘quescol’, firstly, the string’s elements get stored in a list that looks like

[ ‘q’, ‘u’, ‘e’, ‘s’, ‘c’, ‘o’, ‘l’ ]

Then, after using the sorted() function which re-arranges the list elements in ascending order as

[ ‘c’, ‘e’, ‘l’, ‘o’, ‘q’, ‘s’, ‘u’ ]

Finally, the join() function will concatenate the elements of the string and returns the concatenated string as output.

Similar Reads

Hi, Welcome back!
Forgot Password?
Don't have an account?  Register Now