Python program to sort string character in ascending order

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.

Algorithm to sort string in ascending order

Step1:  Start

Step2:  Take string as input from the user.

Step3: Convert string in to the list containg all characters of the string as its element.

Step4: print “ ”.join(sorted(list))

Step5: Stop

Python code to sort string character in ascending order

Output 1:

Python program to sort string in ascending order

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.

Output 2:

Python program to sort string in ascending order

Explanation:

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

[ ‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’, ‘F’, ‘u’, ‘n’ ]

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

 [ ‘F’, ‘P’, ‘h’, ‘n’, ‘n’, ‘o’, ‘t’, ‘u’, ‘y’ ]

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