Python program to sort string in descending order

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

Problem Statement

For the given string as an input by the user, we have to print the characters of the string in descending order.

For example:

Case1: If the user inputs the string ‘python’

Then the output should be ‘ytpnoh’, where all the characters are arranged in descending order .

Case2: If the user inputs the string ‘quescol’

Then the output should be ‘usqolec’, where all characters are arranged in descending order .

Python program to sort string in descending order

  • Our program accepts string input from the user.
  • In order to sort the characters of the string, our program will use the python built-in function ‘sorted()’ and ‘join()’.
  • In ‘join()’ function, our program will pass parameter ‘reverse = True’, which reversed the string.
  • The program execution is done after returning the output as result.

Python program to sort string in descending 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 in reverse order by making ‘reverse = True’
sortedString=''.join(sorted(strList, reverse =True)) 
print("String Sorted in ascending order :", sortedString)

Output:

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

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 with argument ‘reverse =True’ which re-arranges the list elements in descending order as

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

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

What did you think?

Similar Reads

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